In TypeScript, you can define an enum using the enum
keyword. Enums allow you to define a set of named constants, making it easier to work with a set of related values.
Here's an example of how to define an enum in TypeScript:
typescriptenum Direction {
Up,
Down,
Left,
Right
}
In this example, Direction
is the name of the enum, and it consists of four members: Up
, Down
, Left
, and Right
. By default, TypeScript assigns numeric values to each member starting from 0. For example, Up
is 0, Down
is 1, and so on.
You can also explicitly set the values for enum members:
typescriptenum Direction {
Up = 1,
Down = 2,
Left = 3,
Right = 4
}
Now, Up
is 1, Down
is 2, and so on.
Enums in TypeScript can be used in various ways. Here's an example of using the Direction
enum in a function:
typescriptfunction move(direction: Direction): void {
switch (direction) {
case Direction.Up:
console.log('Moving Up');
break;
case Direction.Down:
console.log('Moving Down');
break;
case Direction.Left:
console.log('Moving Left');
break;
case Direction.Right:
console.log('Moving Right');
break;
default:
console.log('Invalid direction');
}
}
// Example usage
move(Direction.Left);
This way, you can use enums to create more readable and self-explanatory code when working with a set of related constants.