Convert an Enum to a Union Type in TypeScript

avatar
Borislav Hadzhiev

Last updated: Jan 20, 2023
2 min

banner

# Convert an Enum to a Union Type in TypeScript

Use a template literal type to convert an enum to a union type.

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;

convert enum to union type

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`;

using template literal type

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 protect us from making a typo when writing out the enum's 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';

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

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev