我们可以使用索引访问类型来查找另一个类型上的特定属性
tsTry
typePerson = {age : number;name : string;alive : boolean };typeAge =Person ["age"];
索引类型本身也是一种类型,因此我们可以使用联合、keyof
或其他类型
tsTry
typeI1 =Person ["age" | "name"];typeI2 =Person [keyofPerson ];typeAliveOrName = "alive" | "name";typeI3 =Person [AliveOrName ];
如果你尝试索引一个不存在的属性,你甚至会看到错误
tsTry
typeProperty 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.I1 =Person ["alve" ];
索引使用任意类型的另一个示例是使用number
获取数组元素的类型。我们可以将它与typeof
结合起来,方便地捕获数组字面量的元素类型
tsTry
constMyArray = [{name : "Alice",age : 15 },{name : "Bob",age : 23 },{name : "Eve",age : 38 },];typePerson = typeofMyArray [number];typeAge = typeofMyArray [number]["age"];// OrtypeAge2 =Person ["age"];
你只能在索引时使用类型,这意味着你不能使用const
来创建变量引用
tsTry
constkey = "age";typeType 'key' cannot be used as an index type.Age =Person []; key
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?2538
2749Type 'key' cannot be used as an index type.
'key' refers to a value, but is being used as a type here. Did you mean 'typeof key'?
但是,你可以使用类型别名来实现类似的重构风格
tsTry
typekey = "age";typeAge =Person [key ];