You can create a union type from a TypeScript enum
by using keyof typeof <enum>
, for example, like so:
enum WeekendDaysEnum { Saturday, Sunday } type WeekendDays = keyof typeof WeekendDaysEnum; // "Saturday" | "Sunday"
This expands the enum
keys into a (case-sensitive) union type, allowing you to use literal string values (derived from concatenating the keys of an enum
):
const day1: WeekendDays = 'Saturday'; const day2: WeekendDays = 'Sunday';
For any value that's not in the union type, TypeScript will show an error:
// Error: Type '"Monday"' is not assignable to type '"Saturday" | "Sunday"'. const day1: WeekendDays = 'Monday'; // Type '"saturday"' is not assignable to type '"Saturday" | "Sunday"'. const day2: WeekendDays = 'saturday';
Hope you found this post useful. It was published . Please show your love and support by sharing this post.