sajad torkamani

In a nutshell

You can use indexed access types to look up the type of another type’s property. For example:

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

Here we access the type of the age property of the Person type using Person["age"].

Recipes

Use unions as an index

type Person = { age: number; name: string; alive: boolean };

type I1 = Person["age" | "name"];
// type I1 = string | number

Use keyof as an index

type Person = { age: number; name: string; alive: boolean };

type I2 = Person[keyof Person];
// type I2 = string | number | boolean

Use another type as an index

type AliveOrName = "alive" | "name";

type I3 = Person[AliveOrName];  
//type I3 = string | boolean

Use number to access the type of an array’s elements

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];

type Person = typeof MyArray[number];
// type Person = { name: string; age: number; }

Here, we’ve managed to look up the type of the elements in MyArray using the special number index.

You can also combine number with another indexed access to look up the type of a property of an array element:

const MyArray = [
  { name: "Alice", age: 15 },
  { name: "Bob", age: 23 },
  { name: "Eve", age: 38 },
];

type Age = typeof MyArray[number]["age"];
// type Age = number

Sources

Tagged: TypeScript

Leave a comment

Your email address will not be published. Required fields are marked *