Horje
TypeScript Enums

TypeScript Enums is a feature that lets you define a group of named constants, which can help you manage and understand your code more easily.

There are two types of Enums in TypeScript:

  • Numeric Enums
  • String Enums

Numeric Enums: Default

Numeric enums are the default in TypeScript. Enums will assign the first value to 0 and then add 1 to every additional value.

Example: In this example, Direction.Up is explicitly set to 0. The following values(Down, Left, Right) are automatically assigned incremental values (1,2,3).

JavaScript
enum Direction {
    Up,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Up;
console.log(move);

Output:

1

Numeric Enums: Initialized

We can set the value of the first enum and the value of the other enums auto increment from that.

Example: In this example, we set the value of the Direction.Up to 1. The following enums (Down, Left, Right) are automatically assigned incremental values (2, 3, 4).

JavaScript
enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}

let move: Direction = Direction.Up;
console.log(move);

Output:

1

Numeric Enums: Fully Initialized

We can assign unique values to every enum value. Then the values will not get incremented automatically.

Example: In this example, we assign values to every enum.

JavaScript
enum Direction {
    Up = 1,
    Down = 3,
    Left = 5,
    Right = 7
}

let move: Direction = Direction.Up;
console.log(move);

Output:

1

String Enums

String Enums are like Numeric strings, but the value assigned to them is in strings.

Example: In this example, we assign a string value to the Enums.

JavaScript
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT"
}

let move: Direction = Direction.Up;
console.log(move);

Output:

"UP"



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What are Closures in JavaScript ? What are Closures in JavaScript ?
What is setTimeout() function in JavaScript ? What is setTimeout() function in JavaScript ?
What is Filter metod in JavaScript ? What is Filter metod in JavaScript ?
How to Check if a Value is NaN ? How to Check if a Value is NaN ?
What is the use of the NaN Value in JavaScript ? What is the use of the NaN Value in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13