Indexed Access Types

We can use an indexed access type to look up a specific property on another type:

  1. type Person = { age: number; name: string; alive: boolean };
    type Age = Person["age"];
    // ^ = type Age = number

The indexing type is itself a type, so we can use unions, keyof, or other types entirely:

  1. type I1 = Person["age" | "name"];
    // ^ = type I1 = string | number
  2. type I2 = Person[keyof Person];
    // ^ = type I2 = string | number | boolean
  3. type AliveOrName = "alive" | "name";
    type I3 = Person[AliveOrName];
    // ^ = type I3 = string | boolean

You’ll even see an error if you try to index a property that doesn’t exist:

  1. type I1 = Person["alve"];
    Property 'alve' does not exist on type 'Person'.2339Property 'alve' does not exist on type 'Person'.

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:

  1. const MyArray = [
    { name: "Alice", age: 15 },
    { name: "Bob", age: 23 },
    { name: "Eve", age: 38 },
    ];
  2. type Person = typeof MyArray[number];
    // ^ = type Person = {
  3. // name: string;
  4. // age: number;
  5. // }
  6. type Age = typeof MyArray[number]["age"];
    // ^ = type Age = number
  7. // Or
    type Age2 = Person["age"];
    // ^ = type Age2 = number