- In TypeScript, an `enum` is a way to define a set of named values as a distinct type. Enums allow you to assign labels to a set of numeric or string values, making it easier to work with these values and improve code readability.
enum Color {
Red,
Green,
Blue,
}
console.log(Color); // Output: { '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
let myColor: Color = Color.Green;
console.log(myColor); // Output: 1
- In this example, we define an enum called `Color` with three members: `Red`, `Green`, and `Blue`. By default, each member of an enum is assigned a numeric value starting from 0 and incremented by 1. So, `Red` has a value of 0, `Green` has a value of 1, and `Blue` has a value of 2.
- We can assign a value from the `Color` enum to a variable, as shown with `myColor = Color.Green`. The variable `myColor` now holds the value `1`, which corresponds to `Green` in the `Color` enum.
- You can also explicitly assign specific numeric values to enum members:
enum Color {
Red = 1,
Green = 2,
Blue = 4,
}
console.log(Color); // Output: { '1': 'Red', '2': 'Green', '4': 'Blue', Red: 1, Green: 2, Blue: 4 }
let myColor: Color = Color.Green;
console.log(myColor); // Output: 2
- In this updated example, we assign specific numeric values to each enum member. Now, `Green` has a value of `2` instead of `1`.
- Enums in TypeScript can also be used with string values:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
console.log(Direction); // Output: { Up: 'UP', Down: 'DOWN', Left: 'LEFT', Right: 'RIGHT' }
let myDirection: Direction = Direction.Up;
console.log(myDirection); // Output: "UP"
- In this case, each member of the `Direction` enum is assigned a string value instead of a numeric value.
- Enums provide a way to define a set of related named values and allow for type-checking during development. They are especially useful when you have a predefined set of options or states that a variable can take.
No comments:
Post a Comment