How to define enum type in Typescript

My favorite way of defining types for enums in TypeScript is simple yet powerful, though slightly counterintuitive. First, we define a const with keys and values, then construct a type from it.

const Animal = {
Dog: 'dog',
Cat: 'cat'
} as const;
type Animal = typeof Animal[keyof typeof Animal];
const Animal = { Dog: 'dog', Cat: 'cat' } as const; type Animal = typeof Animal[keyof typeof Animal];
const Animal = {
   Dog: 'dog',
   Cat: 'cat'
} as const;

type Animal = typeof Animal[keyof typeof Animal];

It may feel counterintuitive because we create both a const and a type with the same name, but it works seamlessly.
We can conveniently use the type like an enum!

if (someAnimal === Animal.Dog) {
...
}
if (someAnimal === Animal.Dog) { ... }
if (someAnimal === Animal.Dog) {
   ...
}

This approach offers autocompletion benefits, aligns with functional programming principles, and has zero runtime overhead (unlike enums).

Leave a Reply

Your email address will not be published. Required fields are marked *