Create a Type from an object's Values in TypeScript

avatar

Borislav Hadzhiev

Fri Mar 11 20222 min read

banner

Photo by Maddie Collet

Create a Type from an object's Values in TypeScript #

To create a type from an object's values:

  1. Use a const assertion when declaring the object.
  2. Use keyof typeof to get a type that represents the object's keys.
  3. Index the object's type at the specific keys to get a type of its values.
index.ts
const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👈️ use const assertion // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys];

The as const syntax is called a const assertion. We used it to declare an immutable object.

We had to do this, because it helps us narrow down the type of the object's values.

index.ts
// 👇️ const employee: { // readonly id: 1; // readonly name: "James Doe"; // readonly salary: 100; // } const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👈️ use const assertion

The values of the object in the example above are typed as 1, James Doe and 100, which is exactly what we need to get a type representing the object's values.

TypeScript is able to be as specific, because it knows that the properties are readonly and the values will never change.

Had we not used a const assertion, we would get much more generic types for the object's values.

index.ts
// 👇️ const employee: { // id: number; // name: string; // salary: number; // } const employee = { id: 1, name: 'James Doe', salary: 100, };

The example above does not use a type assertion, so the type of the object's values would have been string | number, which is probably not what you need.

We used keyof typeof to get the type of the object's keys.

index.ts
const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys];

The keyof typeof syntax returns a type that represents all of the object's keys as strings.

To get a type of the object's values, we used square brackets and indexed the object using the type of the keys.

You can use this approach to get the type of a value that corresponds to a specific property as well.

index.ts
const employee = { id: 1, name: 'James Doe', salary: 100, } as const; // 👇️ type Keys = "id" | "name" | "salary" type Keys = keyof typeof employee; // 👇️ type Values = 1 | "James Doe" | 100 type Values = typeof employee[Keys]; // 👇️ type V1 = 1 type V1 = typeof employee['id']; // 👇️ type V2 = "James Doe" type V2 = typeof employee['name']; // 👇️ type V3 = 100 type V3 = typeof employee['salary'];
Use the search field on my Home Page to filter through my more than 1,000 articles.