Convert an Enum to a Union Type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 14, 2022

banner

Photo from Unsplash

Convert an Enum to a Union Type in TypeScript #

Use a template literal type to convert an enum to a union type, e.g. type ValuesUnion = ${StringEnum}. Template literal types have the same syntax as template literal strings. The union type will contain all of the values of the enum.

index.ts
enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ type ValuesUnion = "S" | "M" | "L" type ValuesUnion = `${StringEnum}`; // 👇️ type KeysUnion = "Small" | "Medium" | "Large" type KeysUnion = keyof typeof StringEnum;

The first example uses a template literal type to get a union type that represents the values of the enum.

Template literal types have the same syntax as template literal strings in JavaScript, but are used in type positions.

index.ts
type T = 'read'; type D = 'draft'; // 👇️ type AllIDs = "read_id" | "draft_id" type AllIDs = `${T | D}_id`;

The second example uses keyof typeof to convert the enum to a union type containing the enum's keys.

index.ts
enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ type KeysUnion = "Small" | "Medium" | "Large" type KeysUnion = keyof typeof StringEnum;

Either of the two approaches would defend us against making a typo when writing out the enums keys or values.

index.ts
enum StringEnum { Small = 'S', Medium = 'M', Large = 'L', } // 👇️ type KeysUnion = "Small" | "Medium" | "Large" type KeysUnion = keyof typeof StringEnum; // ⛔️ Error: Type "Test" is not assignable to type "Small" | "Medium" | "Large" const str: KeysUnion = 'Test';

Because Test is not present in the enum's keys, TypeScript alerts us that we have a typo.

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.