javascript - typescript - ts(7053) : Element implicitly has an 'any' type because expression of type 'string' can't be used to index

标签 javascript typescript interface

在 TypeScript 中,我声明了一个这样的接口(interface):

export default interface MyDTO {
    readonly num: string;
    readonly entitle: string;
    readonly trb: string;
    readonly ucr: string;
    readonly dcr: string;
    readonly udm?: string;
    readonly ddm?: string;
}
使用函数,我想访问属性的值,其名称包含在变量中。
private doSomething(dto: MyDTO, property: string): any {
    let label: any;

    if (['dcr', 'ddm'].includes(property)) {
        label = doSomethingElse(dto[property]);
    } else {
        label = dto[property];
    }
    
    return label;
}
不幸的是,TypeScript 给了我以下错误信息:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyDTO'. No index signature with a parameter of type 'string' was found on type 'MyDTO'.ts(7053)


有人有想法吗?
谢谢

最佳答案

原因是因为MyDTO具有明确命名的属性,但您使用通用字符串作为索引,因此 TypeScript 表示它不能保证将任何字符串传递到您的 doSomething函数实际上将匹配您界面上的属性名称。
TypeScript 2.1 中引入的一个很好的解决方法是 keyof .这使您可以显式键入某些内容作为某个类/接口(interface)的键。
这将 A. 摆脱您看到的 TS 错误,并且 B. 还将检查以确保您的函数的任何调用者实际上传递了一个有效的 key 。

export default interface MyDTO {
    readonly num: string;
    readonly entitle: string;
    readonly trb: string;
    readonly ucr: string;
    readonly dcr: string;
    readonly udm?: string;
    readonly ddm?: string;
}

function doSomething(dto: MyDTO, property: keyof MyDTO): any {
    let label: any;

    if (['dcr', 'ddm'].includes(property)) {
        label = doSomethingElse(dto[property]);
    } else {
        label = dto[property];
    }
    
    return label;
}

doSomething(obj, "foo") // is a TS error
doSomething(obj, "num") // is valid

关于javascript - typescript - ts(7053) : Element implicitly has an 'any' type because expression of type 'string' can't be used to index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62759505/

相关文章:

c# - XmlSerializer 序列化泛型接口(interface)列表

java - 模块化 Java 接口(interface)的正确用法是什么?

javascript - 输入验证 - 如何允许退格键在我的方法中工作

javascript - 是否有适用于 Angular 2 的实时样式指南生成器,很像适用于 React 的样式指南?

javascript - 如何在行为主题上抛出错误并继续流?

typescript - 如何在 Vue 中扩充 `ElementAttrs<HTMLAttributes>` 界面?

javascript - 将unicode php变量传递给javascript

javascript - Rally 类 xtype 值在哪里分配

typescript - 如何获取数组中的常见类型

php - 无法声明在父类(super class)的接口(interface)中声明的子类方法