enum PrintMedia {
Newspaper = 1,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Book = 10
}
function getPrintMediaCode(mediaName: string): number {
if (mediaName === 'newsletter') {
return 5;
}
}
PrintMedia.Newsetter; // returns 5
PrintMedia.Magazine; // returns 15
When the enum includes computed and constant members, then uninitiated enum members either must come first or must come
after other initialized members with numeric constants. The following will give an error.
enum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Newspaper, // Error: Enum member must have initializer
Book,
Magazine = Newsletter * 3,
}
The above enum can be declared as below.
enum PrintMedia {
Newspaper,
Book,
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3
}
// or
enum PrintMedia {
Newsletter = getPrintMediaCode('newsletter'),
Magazine = Newsletter * 3,
Newspaper = 0,
Book,
}
String Enum
It is same as numeric Enum, except that the enum values are initialized with string values.
The benefits of using string enums is that string enums offer better readability. If we were to debug a program, it is easier to read string values rather than numeric values.
enum Actors{ PawanKalyan = "PAWANKALYAN", Chiranjeevi = "CHIRANJEEVI", MaheshBabu = "MAHESHBABU", RamCharan = "RAMCHARAN"}// Access String Enum console.log(Actors.PawanKalyan); console.log(Actors['RamCharan']);
Output:
PAWANKALYAN
RAMCHARAN
In the above example, we have defined a string enum, PrintMedia, with the same values as the numeric enum above, with the difference that these enum values are initialized with string literals. The difference between numeric and string enums is that numeric enum values are auto-incremented, while string enum values need to be individually initialized.
Heterogeneous Enum
Heterogeneous enums are enums that contain both string and numeric value
Example
Reverse Mapping
Enum in TypeScript supports reverse mapping. It means we can access the value of a member and also a member name from its value. Consider the following example.
enum Actors{PawanKalyan = 1,Chiranjeevi,MaheshBabu,RamCharan}console.log(Actors.PawanKalyan);console.log(Actors['RamCharan']);console.log(Actors[3]);Output1 4 MaheshBabu
Let's see how TypeScript implements reverse mapping using the following example.
console.log(Actors);
The above example gives the following output in the browser console.
{ '1': 'PawanKalyan', '2': 'Chiranjeevi', '3': 'MaheshBabu', '4': 'RamCharan', PawanKalyan: 1, Chiranjeevi: 2, MaheshBabu: 3, RamCharan: 4 }
Never
TypeScript introduced a new type which indicates the values that will never occur.
The never type is used when you are sure that something is never going to occur.
Example
No comments:
Post a Comment
Thank you for visiting my blog