Create a Union type from an Object's Values or Keys in TS

avatar

Borislav Hadzhiev

Last updated: Feb 21, 2022

banner

Photo from Unsplash

Create a Union type from an Object's Values or Keys in TS #

To create a union type from an object's values or keys:

  1. Use as const to set the properties of the object to readonly.
  2. Use keyof typeof to get a type of the keys in the object.
  3. Use the keys to get a union of the values.
index.ts
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";} const obj = { name: 'Tom', country: 'Chile', } as const; // 👇️ type UValues = "Tom" | "Chile" type UValues = typeof obj[keyof typeof obj]; // 👇️ type UKeys = "name" | "country" type UKeys = keyof typeof obj;

We used as const to set the properties of the object to readonly and indicate to the language that the type of the expression will not be widened, e.g. from {name: "Tom"} to {name: string}.

The as const syntax is called a const assertion in TypeScript.

The object in the example contains readonly properties, so their values cannot be changed.

index.ts
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";} const obj = { name: 'Tom', country: 'Chile', } as const; // ⛔️ Error: Cannot assign to 'name' because it is a // read-only property. obj.name = 'James';

If you try to change the value of a property, you would get an error.

This way TypeScript can infer the type of the object as {name: 'Tom'; country: 'Chile'} instead of {name: string; country: string;}.

We used keyof typeof to create a union of the object's keys.

index.ts
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";} const obj = { name: 'Tom', country: 'Chile', } as const; // 👇️ type UKeys = "name" | "country" type UKeys = keyof typeof obj;

We can use the same approach to get a union of the object's values.

index.ts
// 👇️ const obj: {readonly name: "Tom"; readonly country: "Chile";} const obj = { name: 'Tom', country: 'Chile', } as const; // 👇️ type UValues = "Tom" | "Chile" type UValues = typeof obj[keyof typeof obj]; // 👇️ type UKeys = "name" | "country" type UKeys = keyof typeof obj;

We used the typeof operator to get the type of the object and then indexed the type of the object with all of the keys to get a union containing the object's values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.