Max Kreutzfeldt

May 25, 2025

Enums and TypeScript

Enums are great for defining fixed sets of values. As you can add meanigful names for each value in the enum, code gets readable and more maintainable. Another nice aspect of enums is, that you can store values at one place.

By default enums are not available in JavaScript. TypeScript is one way to add this data structure to JavaScript. With Typescript you can hold values in enums and even use them for typing.

// Group states in enum.
enum State {
	toDo = 'TODO',
	doing = 'DOING',
	done = 'DONE'
}

// Use enum as type
const logState = (state: State): void => {
	console.log(`State: ${state}`);
};

// Access enum to use a value of it
logState(State.done); // ✅
logState('Done'); // ❌ Type error

In simple cases the usage of union types in TypeScript can be also an option:

// Group states in union type.
type State = 'OPEN' | 'PENDING' | 'CLOSED';

// Union type can only be used for typing.
const state: State = 'PENDING';

If we compare enum and the union type of both examples, the union type can only be used for typing not for accessing values.