首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeScript索引签名类实现

TypeScript索引签名类实现
EN

Stack Overflow用户
提问于 2018-12-19 08:26:03
回答 1查看 855关注 0票数 1

请考虑以下代码片段:

代码语言:javascript
复制
export interface IProduct {
    [key: string]: number | boolean;
}

export class Product implements IProduct {
    b: number;
    c: boolean;
}

我希望TypeScript能够理解如下所示:

嘿,IProduct接口可以是具有任意数量字段的任何类型的对象,这些字段可以通过以下类型之一进行:numberboolean。现在,实现这个接口的类基本上可以包含完全相同的字段变化。

不幸的是,上面的代码给了我错误,该类没有正确地实现接口,迫使我将索引类型重新键入类本身:

代码语言:javascript
复制
export class Product implements IProduct {
    [key: string]:  number | boolean;
    b: number;
    c: boolean;
}

但是老实说,我的期望是我只需要声明类字段,只要它们符合接口声明契约,我就不会出现如下错误:

代码语言:javascript
复制
export class Product implements IProduct {
    b: number;
    c: boolean;
    a: string /* Gives erorr, since string is not allowed index type */
}

对于如何绕过这一点,或者仅仅是我的理解,有什么想法是完全错误的?

EN

回答 1

Stack Overflow用户

发布于 2018-12-19 08:43:31

可以创建强制执行所需约束的类型,但它必须是映射的类型:

代码语言:javascript
复制
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;
}

类型记录抱怨的原因是接口索引签名允许您使用任何字符串进行索引,但是类只有特定的键。如果您的类实际上可以有任何键,那么它应该有索引签名来使其显式化。

编辑

不同的版本,其中接口的泛型类型参数是接口将具有的键:

代码语言:javascript
复制
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();
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53847195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档