【发布时间】:2019-05-19 16:58:22
【问题描述】:
考虑下面的代码 sn-p:
export interface IProduct {
[key: string]: number | boolean;
}
export class Product implements IProduct {
b: number;
c: boolean;
}
我希望 TypeScript 能够像下面这样理解这一点:
嘿,
IProduct接口可以是任何类型的对象 可以是以下类型之一的字段数:number或boolean。现在实现这个接口的类 基本上可以包含完全相同的字段变化
不幸的是,上面的代码给了我错误,该类没有正确实现接口,迫使我将索引类型重新输入到类本身:
export class Product implements IProduct {
[key: string]: number | boolean;
b: number;
c: boolean;
}
但老实说,我的期望是我可以只声明类字段,只要它们符合接口声明合同,我就不会收到如下错误:
export class Product implements IProduct {
b: number;
c: boolean;
a: string /* Gives erorr, since string is not allowed index type */
}
关于如何绕过这个或只是我的理解完全错误的任何想法?
【问题讨论】:
标签: typescript