typescript - 在TypeScript中,如何设置作为类属性的对象的索引签名?

标签 typescript

这是一个类:

export class Survey {
    isCompleted: boolean;
    response: {
        'devices': string[];
        'languages': string[];
        'frameworks': string[];
        'backend': string[];
    };
}

我在尝试以下操作时收到“元素隐式具有‘任何’类型,因为类型‘...’没有索引签名”错误:

return Object.keys(user1.response).map(key => {
        return percentageMatch(user1.response[key], user2.response[key]) * categoryScores[key];
    })

user1user2Survey 类的实例。

我知道如何使用简单的对象文字设置索引签名,但我如何使用 response 对象的属性来设置它,它本身就是 Survey 的一个属性> 类。

最佳答案

这需要将索引类型 [key: string]: string[] 添加到 response 类型:

export class Survey {
    isCompleted: boolean;
    response: {
        [key: string]: string[],
        devices: string[],
        languages: string[],
        frameworks: string[],
        backend: string[],
    };
}

您可以在 TypeScript Playground demo 中查看我创造的。

您还可以考虑减少此处的重复并将已知键提取为字符串文字类型:

type ResponseKeys = 'devices' | 'languages' | 'frameworks' | 'backend';

export class Survey {
    isCompleted: boolean;
    response: {
        [key in ResponseKeys]: string[]
    };
}

关于typescript - 在TypeScript中,如何设置作为类属性的对象的索引签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46554684/

相关文章:

typescript - 由于不允许的 MIME 类型 (“video/mp2t”,TypeScript 中的脚本被阻止)

Angular 6 自定义验证返回类型

typescript - Sonarqube 测试报告 "report refers to a file which is not configured as a test file"当测试和源在一起时

reactjs - 创建 React 应用程序显示 "Cannot use JSX unless the ' --jsx' 标志已提供”

javascript - TypeScript:使用枚举元素而不指定枚举名称

javascript - 如何在 angular2 *ngFor 中的每次迭代中调用组件中的方法?

javascript - Angular 4.0 http put 请求

angular - 将值传递给子组件 Angular 7

javascript - 通过 Object.assign 在 Typescript 类中扩展 `this`

TypeScript Set<> 集合通过索引获取值