E2EHIRING Logo
search

Search blogs by title

Jobs
Jobs
internships
Internships
Company
Partners
mentorship
Mentorship
more
Moredropdown
Login
HomeSepratorIconBlogsSepratorIconTypeScript( Enums)SepratorIcon

TypeScript( Enums)

Han SoloAnbarasan Murugan
calendar11 Jul 2022
poster

TypeScript Enums

  • An enum is a special "class" that represents a group of constants.
  • Enums come in two flavors string and numeric.

Numeric Enums - Default:

By default, enums will initialize the first value to 0 and add 1 to each additional value: 

Example:
enum CardinalDirections {
  North,
  East,
  South,
  West
};
            
let currentDirection = CardinalDirections.North;
console.log(currentDirection);
// Output:0

Numeric Enums - Initialized:

You can set the value of the first numeric enum and have it auto increment from that:

Example:
enum CardinalDirections {
  North = 1,
  East,
  South,
  West
};

console.log(CardinalDirections.North);
console.log(CardinalDirections.West);
//Output :1
//Output: 4


Numeric Enums - Fully Initialized:

You can assign unique number values for each enum value. Then the values will not incremented automatically:

Example:
enum StatusCodes {
  NotFound = 404,
  Success = 200,
  Accepted = 202,
  BadRequest = 400
};

console.log(StatusCodes.NotFound);
console.log(StatusCodes.Success);
//Output:404
//Output:200

String Enums:

Enums can also contain strings  This is more common than numeric enums, because of their readability and intent.

Example:
enum CardinalDirections {
  North = 'North',
  East = "East",
  South = "South",
  West = "West"
};

console.log(CardinalDirections.North);
console.log(CardinalDirections.West);
//Output:North
//output:West

Recent Posts

Innovation is the Need of the Hour: Else you are Outdated

Innovation is the Need of the Hour: Else you are Outdated

Router In React

Router In React

Higher Order Component in React

Higher Order Component in React

Styled Component in React

Styled Component in React

Spring - Bean Life Cycle

Spring - Bean Life Cycle

copycopycopycopy

Han Solo

Recent Posts

Innovation is the Need of the Hour: Else you are Outdated

Innovation is the Need of the Hour: Else you are Outdated

Router In React

Router In React

Higher Order Component in React

Higher Order Component in React

Styled Component in React

Styled Component in React

Spring - Bean Life Cycle

Spring - Bean Life Cycle

e2e logo