Last updated: Feb 26, 2024
Reading timeยท2 min
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.
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.
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.
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.
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.
You can learn more about the related topics by checking out the following tutorials: