In TypeScript, enums are set of named constants. Though it is optional, but enums should be a named group of related constants. TypeScript supports both traditional enums and string-based enums.
1) String-based Enums
Let’s start with string-based enums because they are recommended approach in comparison to traditional enums. Always use string-based enums, until you have a very solid reason for choosing traditional enums over this.
1.1) Syntax
Enum syntax is very similar to other languages e.g. Java.
enum AppStatus { ACTIVE = 'ACTIVE', INACTIVE = 'INACTIVE', ONHOLD = 'ONHOLD' }
Look at the generated code in JavaScript. It has a generated lookup table like this.
var AppStatus; (function (AppStatus) { AppStatus["ACTIVE"] = "ACTIVE"; AppStatus["INACTIVE"] = "INACTIVE"; AppStatus["ONHOLD"] = "ONHOLD"; })(AppStatus || (AppStatus = {}));
1.2) Access enum member values
Use Enum.member
or Enum['member']
format to access enum member values.
enum AppStatus { ACTIVE = 'ACT', INACTIVE = 'INACT', ONHOLD = 'HLD' } AppStatus.ACTIVE //ACT AppStatus.INACTIVE //INACT AppStatus['ACTIVE'] //ACT //Never use numbers with string based enums AppStatus[0] //undefined
1.3) Enum as function argument
To pass enum in functions, declare the argument type of enum itself.
enum AppStatus { ACTIVE = 'ACT', INACTIVE = 'INACT', ONHOLD = 'HLD' } function checkStatus(status: AppStatus): void { console.log(status); } checkStatus(AppStatus.ONHOLD);
2) Traditional number-based enums
Though not recommended, you may come across situations where you need it. So let’s quickly learn.
2.1) Syntax
Syntax is pretty simple and old school. As we have not initialized the values, transpiler generates lookup table with values assigned in array index fashion (starting with zero and then incrementing by one for each member).
enum AppStatus { ACTIVE, //0 INACTIVE, //1 ONHOLD //2 }
If you want to start with any other number, then assign it to the first enum member. All following members will get the value by incrementing one by one.
enum AppStatus { ACTIVE = 5, //5 INACTIVE, //6 ONHOLD //7 }
2.2) Access enum member values
As these are number based enums, you can use the format enum[index_number]
as well, along with Enum.member
or Enum['member']
.
enum AppStatus { ACTIVE, INACTIVE, ONHOLD } console.log(AppStatus.ACTIVE); //0 console.log(AppStatus['INACTIVE']); //1 console.log(AppStatus[0]); //ACTIVE
2.3) Enum as function argument
To pass enum in functions, declare the argument type of enum itself.
enum AppStatus { ACTIVE, INACTIVE, ONHOLD } function checkStatus(status: AppStatus): void { console.log(status); } checkStatus(AppStatus.ONHOLD); //2
Please see the value printed '2'
in last statement. It is not very useful in most of the scenarios, so that’s why string-based enums are preferred and recommended.
Drop me your questions in comments section.
Happy Learning !!