Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too.
In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
There are three types of enums:
Numeric enum: Numeric enums are number-based enums i.e. they store string values as numbers.
String enum: String enums are similar to numeric enums, except that the enum values are initialized with string values rather than numeric 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.
Heterogeneous enum: Heterogeneous enums are enums that contain both string and numeric values.
To check if a value exists in an enum:
Use the Object.values() method to get an array of the enum's values.
Use the includes() method to check if the value exists in the array.
The includes method will return true if the value is contained in the enum and false otherwise.
//For String Enums
enum Sizes
{
Small = 'S',
Medium = 'M',
Large = 'L',
}
const keys = Object.keys(Sizes);
console.log(keys); // ['Small', 'Medium', 'Large']
const values = Object.values(Sizes);
console.log(values); // ['S', 'M', 'L']
if (values.includes('S' as unknown as Sizes))
{
console.log('Value exists in enum');
}
// For Numeric Enums
enum SizesNumeric
{
Small,
Medium,
Large,
}
if (2 in SizesNumeric)
{
console.log(SizesNumeric[2]); // "Large"
}
Enums in TypeScript are real objects and exist at runtime. This is why we are able to pass an enum to the Object.keys and Object.values methods.
The methods return an array containing the object's keys and values, on which we can use the includes method to check if a specific value is contained in the enum's values.
Advantages of using Enum in Typescript:
Provides flexibility making it easier to express and document intentions and use cases.
Saves compile-time and runtime with inline code in JavaScript.
Allows for the creation of memory-efficient custom constants in JavaScript.
The Tech Platform
Comments