【发布时间】:2015-11-10 22:28:44
【问题描述】:
在http://www.typescriptlang.org/Handbook#interfaces-array-types 这是什么意思 “限制从数字索引返回的类型必须是从字符串索引返回的类型的子类型。”
谁能举个例子?
【问题讨论】:
标签: typescript
在http://www.typescriptlang.org/Handbook#interfaces-array-types 这是什么意思 “限制从数字索引返回的类型必须是从字符串索引返回的类型的子类型。”
谁能举个例子?
【问题讨论】:
标签: typescript
仅供参考,有两种类型的索引签名,字符串和数字。
字符串索引签名:
[index: string]: SomeType
这表示当我通过字符串索引访问此对象的属性时,该属性将具有SomeType 类型。
数字索引签名:
[index: number]: SomeOtherType
这表示当我通过数字索引访问此对象的属性时,该属性将具有SomeOtherType 类型。
需要明确的是,通过字符串索引访问属性是这样的:
a["something"]
按数字索引:
a[123]
您可以同时定义字符串索引签名和数字索引签名,但数字索引的类型必须与字符串索引相同,或者必须是字符串索引返回的类型的子类。
所以,这没关系:
interface SomeInterface {
[index: string]: Fruit;
[index: number]: Fruit;
}
因为两个索引签名具有相同的类型Fruit。但你也可以这样做:
interface SomeInterface {
[index: string]: Fruit;
[index: number]: Apple;
}
只要Apple 是Fruit 的子类。
【讨论】: