Enums
Learn how to use TypeScript enums to define named value sets for variables or function parameters.
We'll cover the following...
Introduction to enums
Enums are a special type whose concept is similar to other languages, such as C#, C++, or Java, and provides the solution to the problem of special numbers or special strings.
Enums are used to define a human-readable name for a specific number or string.
Consider the following code:
// Define an enum with the values 'Open' and 'Closed'enum DoorState {Open,Closed}// Declare a function that takes an argument of type 'DoorState'function checkDoorState(state: DoorState) {// Print the enum value to the consoleconsole.log(`enum value is : ${state}`);// Use a switch statement to check the value of 'state'switch (state) {// If 'state' is 'Open', print a message to the consolecase DoorState.Open:console.log(`Door is open`);break;// If 'state' is 'Closed', print a message to the consolecase DoorState.Closed:console.log(`Door is closed`);break;}}
Defining enum DoorState
-
We start by using the
enum
keyword to define an enum namedDoorState
on line 2. Thisenum
has two possible values, eitherOpen
orClosed
. -
We then have a function named
checkDoorState
on lines 8–23 that has a single parameter namedstate
of typeDoorState
. This means that the ...