在名为的文件中给出以下代码test.ts
:
interface ImageFile {
width: number;
height: number;
url: string;
}
interface ImageFiles {
low: ImageFile;
medium?: ImageFile;
high?: ImageFile;
}
let images: ImageFiles = {
low: {
width: 0,
height: 0,
url: 'bla'
}
};
Object.keys(images).forEach((k) => {
let img = images[k];
// do something with img
});
使用--noImplicitAny选项进行编译时,出现以下错误:
$ tsc test.ts --noImplicitAny
test.ts(22,10): error TS7017: Index signature of object type implicitly has an 'any' type.
这意味着images[k]
类型隐式具有any
类型,并且类型转换在这里不起作用。
没有--noImplicitAny
标志的编译工作正常。
设置以上标志后,如何正确遍历对象?
TypeScript编译器无法推断的正确类型images[k]
,这就是它抱怨的原因。如您所知,类型转换不能解决问题。
相反,您可以使用索引签名来告诉编译器ImageFiles
对象的所有属性都具有以下类型ImageFile
:
interface ImageFiles {
[key: string]: ImageFile;
low: ImageFile;
medium?: ImageFile;
high?: ImageFile;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句