我很难理解这一点:
支持的索引类型有两种:字符串和数字。可以支持两种类型的索引,但限制是从数字索引返回的类型必须是从字符串索引返回的类型的子类型。
虽然索引签名是一种描述数组和“字典”模式的强大方式,但它们也强制所有属性匹配它们的返回类型。在这个例子中,属性与更一般的索引不匹配,类型检查器给出错误:
Run Code Online (Sandbox Code Playgroud)interface Dictionary { [index: string]: string; length: number; // error, the type of 'length' is not a subtype of the indexer }
我已经尝试了 4 个案例,但仍然无法理解发生了什么。有人会解释为什么只有[index: string]: string;错误 TS2411 吗?

另一个案例:
如果您拥有[index: string]: string; 所有属性,则必须是string. 因此:
interface Dictionary {
[index: string]: string;
length: number; // error, length is not a string.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2703 次 |
| 最近记录: |