我们可以使用索引访问类型在另一个类型上查找特定的属性:
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"];// 或者typeAge2 =Person ["age"];
在进行索引时,你只能使用类型,这意味着不能使用 const
来进行变量引用:
tsTry
constkey = "age";typeType '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'?2538Age =Person []; key
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 ];