typescript 可分配给类型“never”的类型

vohkndzv  于 7个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(84)

在下面的例子中,有人知道如何编写field变量,使其符合给定的接口(因此我们不应该改变接口)吗?现在我得到一个错误,说Type '{ accountId: string; active: true; }[]' is not assignable to type 'never'.

interface Fields {
    votes: Votes & {
        voters: never;
    };
}

interface Votes {
    self: string;
    votes: number;
    hasVoted: boolean;
    voters: User[];
}

interface User {
    accountId: string;
    active: boolean;
}

const field: Fields = {
    votes: {
        self: "self",
        votes: 0,
        hasVoted: false,
        voters: [
            {
                accountId: "accountId",
                active: true,
            },
        ],
    },
};

字符串

t3psigkw

t3psigkw1#

never不能赋值任何东西,所以你必须使用类型Assert来强制它。例如:

const fields: Fields = {
    votes: {
        self: "self",
        votes: 0,
        hasVoted: false,
        voters: [
            {
                accountId: "accountId",
                active: true,
            },
        ] as Fields["votes"]["voters"], // <=============
    },
};

字符串
Playground链接

相关问题