如何防止错误“对象类型的索引签名隐式具有“任何"类型"?在启用 noImplicitAny 标志的情况下编译打字稿时? [英] How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?
问题描述
我总是使用 --noImplicitAny 标志编译 Typescript.这是有道理的,因为我希望我的类型检查尽可能严格.
I always compile Typescript with the flag --noImplicitAny. This makes sense as I want my type checking to be as tight as possible.
我的问题是,使用以下代码我得到错误对象类型的索引签名隐式具有任何"类型
:
My problem is that with the following code I get the error Index signature of object type implicitly has an 'any' type
:
interface ISomeObject {
firstKey: string;
secondKey: string;
thirdKey: string;
}
let someObject: ISomeObject = {
firstKey: 'firstValue',
secondKey: 'secondValue',
thirdKey: 'thirdValue'
};
let key: string = 'secondKey';
let secondValue: string = someObject[key];
需要注意的是,这个想法是键变量来自应用程序中的其他地方,并且可以是对象中的任何键.
Important to note is that the idea is that the key variable comes from somewhere else in the application and can be any of the keys in the object.
我已经尝试通过以下方式显式转换类型:
I've tried explicitly casting the type by:
let secondValue: string = <string>someObject[key];
或者我的场景是不是用 --noImplicitAny
是不可能的?
Or is my scenario just not possible with --noImplicitAny
?
推荐答案
添加索引签名会让 TypeScript 知道应该是什么类型.
Adding an index signature will let TypeScript know what the type should be.
在你的情况下,这将是 [key: string]: string;
In your case that would be [key: string]: string;
interface ISomeObject {
firstKey: string;
secondKey: string;
thirdKey: string;
[key: string]: string;
}
然而,这也强制所有属性类型匹配索引签名.由于所有属性都是 string
,所以它可以工作.
However, this also enforces all of the property types to match the index signature. Since all of the properties are a string
it works.
虽然索引签名是一种描述数组和字典"模式的强大方式,但它们也强制所有属性匹配它们的返回类型.
While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type.
如果类型不匹配,可以使用联合类型[key: string]: string|IOtherObject;
If the types don't match, a union type can be used [key: string]: string|IOtherObject;
对于联合类型,最好让 TypeScript 推断类型而不是定义类型.
With union types, it's better if you let TypeScript infer the type instead of defining it.
// Type of `secondValue` is `string|IOtherObject`
let secondValue = someObject[key];
// Type of `foo` is `string`
let foo = secondValue + '';
尽管如果索引签名中有很多不同的类型,这可能会有点混乱.另一种方法是在签名中使用 any
.[key: string]: any;
然后你需要像上面那样转换类型.
Although that can get a little messy if you have a lot of different types in the index signatures. The alternative to that is to use any
in the signature. [key: string]: any;
Then you would need to cast the types like you did above.
这篇关于如何防止错误“对象类型的索引签名隐式具有“任何"类型"?在启用 noImplicitAny 标志的情况下编译打字稿时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!