在下面的例子中,有人知道如何编写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,
            },
        ],
    },
};

推荐答案

Nothing is assignable to never,所以您必须用类型断言来强制它.例如:

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

Playground link

Typescript相关问答推荐

将对象属性路径描述为字符串数组的类型

TS 2339:属性切片不存在于类型DeliverableSignal产品[]上>'

React Hook中基于动态收件箱定义和断言回报类型

如何使用axios在前端显示错误体

TypeScript将键传递给新对象错误

如何缩小变量访问的对象属性范围?

contextPaneTitleText类型的参数不能分配给remoteconfig类型的关键参数'""'''

Angular 15使用react 式表单在数组内部创建动态表单数组

部分更新类型的类型相等

如何在方法中正确地传递来自TypeScrip对象的字段子集?

我在Angular 17中的environment.ts文件中得到了一个属性端点错误

有没有办法传递泛型类型数组,以便推断每个元素的泛型类型?

打字错误TS2305:模块常量没有导出的成员

为什么我的函数arg得到类型为Never?

KeyOf关键字在特定示例中是如何工作的

为什么TypeScrip假定{...省略类型,缺少类型,...选取类型,添加&>}为省略类型,缺少类型?

如何在TypeScrip中使用数组作为字符串的封闭列表?

如何从抽象类的静态方法创建子类的实例?

替换typescript错误;X类型的表达式可以';t用于索引类型Y;带有未定义

必须从注入上下文调用Angular ResolveFn-inject()