We can use an indexed access type to look up a specific property on another type:
Try
typePerson = {age : number;name : string;alive : boolean };type// ^ = type Age = numberAge =Person ["age"];
The indexing type is itself a type, so we can use unions, keyof
, or other types entirely:
type// ^ = type I1 = string | numberI1 =Person ["age" | "name"];
type// ^ = type I2 = string | number | booleanI2 =Person [keyofPerson ];Try
typeAliveOrName = "alive" | "name";type// ^ = type I3 = string | booleanI3 =Person [AliveOrName ];
You’ll even see an error if you try to index a property that doesn’t exist:
Try
typeProperty 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.I1 =Person ["alve" ];
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:
constMyArray = [{name : "Alice",age : 15 },{name : "Bob",age : 23 },{name : "Eve",age : 38 },];
type// ^ = type Person = {Person = typeofMyArray [number];// name: string;
// age: number;
// }
type// ^ = type Age = numberAge = typeofMyArray [number]["age"];Try
// Ortype// ^ = type Age2 = numberAge2 =Person ["age"];