Enums and union literal types both let you define a set of fixed values. They help keep your code clear and safe by limiting what values a variable can have.
0
0
Enum vs union literal type trade-offs in Typescript
Introduction
When you want a group of named constants that are easy to read and use.
When you need to restrict a variable to a few specific string or number values.
When you want better autocompletion and error checking in your code editor.
When you want to use values that can be checked at compile time without extra code.
When you want to keep your code simple and avoid extra generated code.
Syntax
Typescript
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
// vs
type Color = "RED" | "GREEN" | "BLUE";Enum creates a named object with values you can use.
Union literal type defines a type that can only be one of the listed values.
Examples
Enum with numbers starting at 1. Values auto-increment.
Typescript
enum Direction {
Up = 1,
Down,
Left,
Right
}Union literal type with string values.
Typescript
type Direction = "Up" | "Down" | "Left" | "Right";
Enum with string values and usage example.
Typescript
enum Status {
Success = "SUCCESS",
Failure = "FAILURE"
}
const s: Status = Status.Success;Union literal type with usage example.
Typescript
type Status = "SUCCESS" | "FAILURE"; const s: Status = "SUCCESS";
Sample Program
This program shows how to use both enum and union literal type to restrict values and print them.
Typescript
enum Fruit {
Apple = "APPLE",
Banana = "BANANA",
Cherry = "CHERRY"
}
function printFruit(fruit: Fruit) {
console.log(`You chose: ${fruit}`);
}
printFruit(Fruit.Banana);
// Using union literal type
type FruitType = "APPLE" | "BANANA" | "CHERRY";
function printFruitType(fruit: FruitType) {
console.log(`You chose: ${fruit}`);
}
printFruitType("CHERRY");OutputSuccess
Important Notes
Enums generate extra JavaScript code, union types do not.
Union literal types are simpler and often preferred for string sets.
Enums can be easier to use when you want named constants grouped together.
Summary
Enums create named objects with fixed values and generate code.
Union literal types restrict values without extra code and are simpler.
Choose based on whether you want runtime objects (enum) or just type safety (union).