Literal Types & Enums
8 min read
Literal Types & Enums
Literal types
A literal type constrains a variable to an exact value rather than a broad primitive. String, number, and boolean literals are all supported.
ts
type Direction = "north" | "south" | "east" | "west";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Toggle = true | false; // equivalent to boolean
function move(dir: Direction) {
console.log("Moving:", dir);
}
move("north"); // OK
move("up"); // Error — not in the unionEnums
Enums declare a set of named constants. Unlike literal type unions, numeric enums produce actual JavaScript output. Const enums are fully erased at compile time.
ts
// Numeric enum (compiled to an object)
enum Role {
Student, // 0
Mentor, // 1
Admin // 2
}
// String enum (safer for serialization)
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
// Const enum (inlined, no runtime object)
const enum HttpStatus {
OK = 200,
NotFound = 404,
InternalError = 500
}
const status: HttpStatus = HttpStatus.OK; // compiled to: const status = 200Many TypeScript practitioners prefer literal union types ("red" | "green" | "blue") over enums because they are simpler, have no runtime footprint, and serialize naturally. Use enums when you need auto-incremented numbers or need to iterate over values.
Ready to test yourself?
Practice TypeScript— quiz & coding exercises