我们可以使用索引访问类型来查找另一种类型的特定属性:
¥We can use an indexed access type to look up a specific property on another type:
tsTrytypePerson = {age : number;name : string;alive : boolean };typeAge =Person ["age"];
索引类型本身就是一种类型,所以我们可以完全使用联合、keyof 或其他类型:
¥The indexing type is itself a type, so we can use unions, keyof, or other types entirely:
tsTrytypeI1 =Person ["age" | "name"];typeI2 =Person [keyofPerson ];typeAliveOrName = "alive" | "name";typeI3 =Person [AliveOrName ];
如果你尝试索引不存在的属性,你甚至会看到错误:
¥You’ll even see an error if you try to index a property that doesn’t exist:
tsTrytypeProperty 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.I1 =Person ["alve" ];
使用任意类型进行索引的另一个示例是使用 number 来获取数组元素的类型。我们可以将它与 typeof 结合起来,以方便地捕获数组字面量的元素类型:
¥Another example of indexing with an arbitrary type is using number to get the type of an array’s elements.
We can combine this with typeof to conveniently capture the element type of an array literal:
tsTryconstMyArray = [{name : "Alice",age : 15 },{name : "Bob",age : 23 },{name : "Eve",age : 38 },];typePerson = typeofMyArray [number];typeAge = typeofMyArray [number]["age"];// OrtypeAge2 =Person ["age"];
你只能在索引时使用类型,这意味着你不能使用 const 来进行变量引用:
¥You can only use types when indexing, meaning you can’t use a const to make a variable reference:
tsTryconstkey = "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'?
但是,你可以将类型别名用于类似样式的重构:
¥However, you can use a type alias for a similar style of refactor:
tsTrytypekey = "age";typeAge =Person [key ];