How to Create a Union Type From Enum Keys in TypeScript?

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

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.