Sat Jan 28 2023
How to convert TypeScript Enum to a Union Type
An explanation of 2 easy ways to convert a TypeScript Enum to a Union Type
I'm usually not in the habit of creating a lot of Enums these days as I find more comfort in using Unions as they give enhanced type safety by limiting what a property could be.
This blog post came about because I was creating an interface for the props of a React component and wanted to limit the type of a property in this interface to the values contained within the Enum.
There are two ways to do this
Let's consider the below as the Enum in question
1enum Directions {2 left = "left",3 right = "right",4 straight = "straight",5}
If I wanted to convert the above into a type I have 2 options
Using the keyof typeof
2. Using a template literal to convert the Enum
Both of the above ways should now give you type safety. Take a look below on how we cannot assign a value that is not within our original Enum
1enum Directions {2 left = "left",3 right = "right",4 straight = "straight",5}6type DirectionsUnion = `${Directions}`;7// ✅ all clear8let directionOne: DirectionsUnion = "left";9// ⛔️ Error: Type '"meow"' is not assignable to type '"left" | "right" | "straight"'.10let newDirection: DirectionsUnion = "meow";
Hope you found this useful! If there is anything you'd like me to write about more, let me know in the comments below!