我想创建一个对象接口(interface),强制使用字符串作为键,但 TypeScript 编译器传递代码,即使它有数字类型作为键。为什么?
例如,
interface PriceI {
[key:string]:number;
}
var coursePrice: PriceI = {};
coursePrice["Orange"] = 100;
coursePrice["Apple"] = 200;
coursePrice[3]=200; // It should be compile error, but it pass
coursePrice[true]=300; // It's compile error
最佳答案
参见the handbook :
There are two types of supported index signatures: string and number. It is possible to support both types of indexers, but the type returned from a numeric indexer must be a subtype of the type returned from the string indexer. This is because when indexing with a
number
, JavaScript will actually convert that to astring
before indexing into an object. That means that indexing with100
(anumber
) is the same thing as indexing with"100"
(astring
), so the two need to be consistent.
在您的示例中,TypeScript 认为 coursePrice[3] = 200;
相当于 coursePrice["3"] = 200;
。
关于javascript - 如何在 TypeScript 界面中强制键类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37069430/