Skip to content
Nate
Stephens

Indexed Access Types

The concept is you grab a piece of type information from another type using something that feels like a property key.

Indexed Access types provide a mechanism for retrieving parts of an array or object type via indices.

interface Car {
  make: string;
  model: string;
  year: number;
  color: {
    red: string;
    green: string;
    blue: string;
  };
}

let carColor: Car['color'];
// let carColor: {
//   red: string;
//   green: string;
//   blue: string;
// };

You can also reach deeper into the object through multiple “accesses”:

let carColorRedComponent: Car['color']['red'];
// let carColorRedComponent: string;

You can pass or project a union type (|) through Car as an index, as long as all parts of the union type are each a valid index:

let carProperty: Car['year' | 'color'];
// let carProperty:
//   | number
//   | {
//       red: string;
//       green: string;
//       blue: string;
//     };

Using keyof

You can access all the property value types by using keyof.

type Obj = {
  a: 'A';
  b: 'B';
  c: number;
};

type Values = Obj[keyof Obj];
// Inferred Type: number | "A" | "B"

From the Intermediate TypeScript course on FEM taught by Mike North.

From the React and TypeScript, v2 course on FEM taught by Steve Kinney.


Last Updated: