我正在通过阅读来学习 Typescript这份官方文件 https://www.typescriptlang.org/docs/handbook/interfaces.html关于索引器类型。
我无法理解这段代码:
interface NumberDictionary {
[index: string]: number;
length: number; // ok, length is a number
name: string; // error, the type of 'name' is not a subtype of the indexer
}
First,为什么要把“长度”放在索引类型中???
let myDict : NumberDictionary;
myDict[10] = 23;
NumberDictionary 是一种索引类型。为什么 NumberDictionary 定义中有长度?索引类型应该是a[10],为什么有长度? javascript中的数组对象有长度,但索引类型是数组吗?如果是这样,为什么上面的例子定义了长度?有必要吗?
抱歉我的咆哮。你可以看到我很困惑。
Second,
name: string;// error, the type of 'name' is not a subtype of the indexer
我不明白这一行的评论。为什么名称必须是索引器的子类型?索引器就像a[10] = "Tom",那么索引器的子类型是什么?
我不明白这一行的评论。为什么名称必须是索引器的子类型?
因为对于任何string
访问 TypeScript 将假定类型number
(基于[index: string]: number;
)。因此,如果name: string;
被允许以下假设number
但实际上你可能会认为string:
let x: NamedDictionary = Object.create(null);
let n = "name";
let y = x[n]; // TypeScript assumes `number`
let z = x["name"]; // Would you want `string`?
查看之间的不一致y
and z
^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)