Create a Union type from an Array in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 21, 2022

banner

Photo from Unsplash

Create a Union type from an Array in TypeScript #

To create a union type from an array:

  1. Use as const to convert the array into a readonly tuple.
  2. Use typeof arr[number] to get a type containing all of the array's elements.
  3. The resulting type will be a union of all of the elements in the array.
index.ts
// 👇️ const sizes: readonly ["small", "medium", "large"] const sizes = ['small', 'medium', 'large'] as const; // 👇️ type SizesUnion = "small" | "medium" | "large" type SizesUnion = typeof sizes[number];

We used as const to set the properties of the array to readonly and indicate to the language that the type of the expression will not be widened, e.g. from ['small', 'medium'] to string[].

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

The array in the example becomes a readonly tuple, so its contents cannot be changed.

index.ts
// 👇️ const sizes: readonly ["small", "medium", "large"] const sizes = ['small', 'medium', 'large'] as const; // ⛔️ Error: Property 'push' does not exist // on type 'readonly ["small", "medium", "large"]' sizes.push('test');

If you try to change the contents of the array, you would get an error.

This way TypeScript can infer the type of the array as ['small', 'medium', 'large'] and not string[].

The typeof operator allows us to get the type of a variable.

index.ts
// 👇️ const sizes: readonly ["small", "medium", "large"] const sizes = ['small', 'medium', 'large'] as const; // 👇️ type SizesUnion = "small" | "medium" | "large" type SizesUnion = typeof sizes[number]; // 👇️ type T = readonly ["small", "medium", "large"] type T = typeof sizes;

Arrays have a numeric index signature.

index.ts
// 👇️ const sizes: readonly ["small", "medium", "large"] const sizes = ['small', 'medium', 'large'] as const; // 👇️ ['0', '1', '2'] console.log(Object.keys(sizes));

This is why we used the [number] syntax to get a union containing all of the values in the array.

We are basically getting all of the values in the array that can be indexed with a number key.

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.