Enums
An enum defines a fixed set of named values — useful whenever a variable should only ever be one of a small, known set of options, like a status or a direction.
main.ts
Try it yourself →enum Status {
Pending,
Active,
Completed,
}
let current: Status = Status.Active;
console.log(current);
console.log(Status[current]);Output
1 Active
By default, enum members are numbered starting from 0 — Status.Pending is 0, Status.Active is 1, and so on. Status[current] looks the number back up to its name.
String enums
A string enum gives each member an explicit string value instead, which is often clearer when you might log or serialize the value somewhere.
main.ts
Try it yourself →enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
let move: Direction = Direction.Left;
console.log(move);Output
LEFT
Next: classes and objects — bundling data and behavior together, with TypeScript's access modifiers.
Practice exercise
Define a string enum Light with Red = "STOP" and Green = "GO". Set a variable signal to Light.Green and print it.