在 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/