enum
in TypeScriptAn enum
(short for enumeration) is a special data type in TypeScript that allows you to define a set of named constants.
It makes the code more readable and easier to manage when dealing with fixed sets of related values.
enum Direction {
North,
South,
East,
West
}
By default, enums start numbering from 0
.
let move: Direction = Direction.North;
console.log(move); // Output: 0
You can assign custom values to enum members.
enum Status {
Success = 1,
Error = -1,
Pending = 0
}
let result: Status = Status.Success;
console.log(result); // Output: 1
Enums can also have string values.
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
let favColor: Color = Color.Green;
console.log(favColor); // Output: "GREEN"
const result = (
name: "Sanket",
marks: 98
)
The type of the above raw object is inferred as:
{
name: string;
marks: number;
}
Something like the given object below: