请考虑以下代码片段:
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 */
}对于如何绕过这一点,或者仅仅是我的理解,有什么想法是完全错误的?
发布于 2018-12-19 08:43:31
可以创建强制执行所需约束的类型,但它必须是映射的类型:
export type IProduct<T> = Record<keyof T, number | boolean>
// Or, same effect but using the actual mapped type
// export type IProduct<T> = {
// [P in keyof T]: number | boolean;
//}
export class Product implements IProduct<Product> {
b: number;
c: boolean;
}类型记录抱怨的原因是接口索引签名允许您使用任何字符串进行索引,但是类只有特定的键。如果您的类实际上可以有任何键,那么它应该有索引签名来使其显式化。
编辑
不同的版本,其中接口的泛型类型参数是接口将具有的键:
export type IProduct<T extends PropertyKey> = Record<T, number | boolean>
export class Product implements IProduct<keyof Product> {
b: number;
c: boolean;
}
let o: IProduct<'c' | 'b'> = new Product();https://stackoverflow.com/questions/53847195
复制相似问题