An enum in TypeScript is a way to define a set of named constants. An enum is a set of named numeric constants, which are assigned values by default, starting from 0. You can also specify your own values for each constant in the enum.
Here's an example of an enum in TypeScript:
enum Color { Red, Green, Blue }
let myColor: Color = Color.Red;
console.log(myColor); // outputs: 0
In this example, an enum named Color is defined with three constants: Red, Green, and Blue. By default, the first constant Red is assigned the value 0, the second constant Green is assigned the value 1, and the third constant Blue is assigned the value 2. You can access the values of the constants using the dot notation, as in Color.Red.
You can also specify your own values for each constant in the enum:
enum Size { Small = 6, Medium = 8, Large = 10 }
let mySize: Size = Size.Small;
console.log(mySize); // outputs: 6
In this example, the enum Size is defined with three constants Small, Medium, and Large, each with a specific numeric value. The value of each constant can be accessed in the same way as before, using the dot notation.
Enums are useful in many cases, such as when you want to define a set of named constants that can be used throughout your code, or when you want to create a type that can only take a set of specific values.
Enums
An
enum
in TypeScript is a way to define a set of named constants. An enum is a set of named numeric constants, which are assigned values by default, starting from 0. You can also specify your own values for each constant in theenum
.Here's an example of an enum in TypeScript:
In this example, an
enum
named Color is defined with three constants:Red, Green, and Blue
. By default, the first constantRed
is assigned the value0
, the second constantGreen
is assigned the value1
, and the third constantBlue
is assigned the value2
. You can access the values of the constants using the dot notation, as inColor.Red
.You can also specify your own values for each constant in the
enum
:In this example, the enum
Size
is defined with three constantsSmall, Medium, and Large
, each with a specific numeric value. The value of each constant can be accessed in the same way as before, using the dot notation.Enums are useful in many cases, such as when you want to define a set of named constants that can be used throughout your code, or when you want to create a type that can only take a set of specific values.