我很难理解这一点:
There are two types of supported index types: string and number. It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.
While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type. In this example, the property does not match the more general index, and the type-checker gives an error:
interface Dictionary { [index: string]: string; length: number; // error, the type of 'length' is not a subtype of the indexer }
来源:TypeScript Handbook's interface
我已经尝试了 4 个案例,但仍然无法理解发生了什么。谁能解释为什么只有 [index: string]: string;
会有错误 TS2411?
另一种情况:
最佳答案
如果您有 [index: string]: string;
所有属性都必须是 string
。因此:
interface Dictionary {
[index: string]: string;
length: number; // error, length is not a string.
}
关于TypeScript 接口(interface)数组类型错误 TS2411,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33818178/