TypeScript Enums Type is not natively supported by Javascript, but it's a notable feature of the Typescript Programming language. In general, enumerations shortly called "enum" are available in most programming languages to create named consonants. Enums allow us to create a set of named constants, making it easier for us by being self-explanatory while declaring a set of predefined values.
Syntax:
enum enum_name {
constant_name = value,
... so on
}
Parameters:
- enum is the keyword itself which is used to start the enum.
- enum_name is the name given to the enum type variable.
- constant_name is the variable name that should be declared inside of the enum.
- value is the value given to that constant_name variable.
Different types of the Enums:
- Numeric enum: In numeric enums, we can declare the first value, after that all of the following members are auto-incremented by one from that point on.
- String enum: String enums also follow a similar concept, but have some subtle runtime differences. In string enums, we don't have the concept of auto-incrementing, but it has benefits like giving a meaningful and readable value when your code runs by "serializing" and independent of the enum member itself.
- Heterogenous Enums: We can mix up the constant datatype with string and number members, but it is not advisable to do so. Generally, a set of predefined constants will always be the same datatype. To declare a heterogenous enum, initialize constants with different data types like string and number while declaring the enum.
- Computed and Constant members: Each enum member can either be a constant or computed value. To be a constant value it has to satisfy any of the three following conditions, if any of the expressions doesn't fall under any of the three rules then it will be a computed member.
- It is the first member of the enum and it has no initializer, so by default, it is assigned 0.
- Members which have no initializer but the previous constants are numeric constants.
- Union enums and enum member types: Within constant enum sets, there exists a unique category known as "literal enum members." These members do not require computation and fall into one of these two categories:
- Enums at runtime:
- They have no assigned value, remaining uninitialized.
- Their values are initialized using string literals like "apple," "banana," or "cherry."
- They are initialized with numeric literals, such as 5, 42, or by applying a unary minus to a numeric literal (e.g., -7 or -99).
- Enums at compile time: Even though, enums are exists as objects at runtime, the "keyof" keyword works differently than its usual behaviour with a typical object. To make the "keyof" to respond to a enum like a typical object, we have to append a one more keyword "typeof" to get the type that represents all the enum keys as strings.
- Ambient enums: It is used to create a already existing enum type enum.
- Objects vs Enums: Objects and enums have distinct roles in programming. Objects embody specific instances within a class, whereas enums establish a collection of named, unchanging values.
Example 1: In this example, we will use the numeric enums to store the discount percentage for various cards in a enum, as the discount are tends to be constant storing inside a enum increases the readability and understandability of the code.
JavaScript
// Discount percentage enum
// set of constants of
// discounts based on type of card
enum discount {
STANDARD = 0.05,
GOLD = 0.1,
PLATINUM = 0.2,
DIAMOND = 0.3,
}
// Function to get the net
// cost after the discount
function
getNetCost(cardTYpe: string,
amount: number): number {
if (cardTYpe === "GOLD") {
return amount -
(amount * discount.GOLD)
} else if (cardTYpe === "PLATINUM") {
return amount -
(amount * discount.PLATINUM)
} else if (cardTYpe === "DIAMOND") {
return amount -
(amount * discount.DIAMOND)
} else {
return amount -
(amount * discount.STANDARD)
}
}
// calculating the net cost with the function
// and logging the result value
console.log(getNetCost("PLATINUM", 1000))
Output:
Numeric Enum ExampleExample 2: In this example, we will use the String enums to store a set of predefined string literals under a enum.
JavaScript
// Typescript code for String enums
// Department enum contains
// various department string literals
enum Department {
CSE = "COMPUTER SCIENCE ENGINEERING",
IT = "INFORMATION TECHNOLOGY",
MECH = "MECHANICAL ENGINEERING"
}
// Initializing the myDepartment
// const with enum value or get choice
// from user and pick value based on those
// from enum
const myDepartment: Department = Department.IT
// Logging out my department value
console.log(`My department is ${myDepartment}`)
Output:
String Enums exampleConclusion: Enums can be used to create more readable and self-explanatory code, especially when dealing with sets of constants. However, it's important to be aware that enums are compiled to JavaScript and can introduce some runtime overhead. Additionally, numeric enums can sometimes lead to unexpected behavior if not used carefully, so it's a good practice to assign values explicitly to enum members when necessary.
Similar Reads
TypeScript Enums TypeScript Enums allows you to create a list of constants (unchanging variables) and give them easy-to-remember names. These names make your code easier to read and understand by grouping related values together under one name. Enums can use both numbers and text, so you can choose what works best f
4 min read
Data types in TypeScript In TypeScript, a data type defines the kind of values a variable can hold, ensuring type safety and enhancing code clarity.Primitive Types: Basic types like number, string, boolean, null, undefined, and symbol.Object Types: Complex structures including arrays, classes, interfaces, and functions.Prim
3 min read
TypeScript Custom Type Guards TypeScript boasts a powerful type system, which helps the developers catch errors at compile time and write more resilient code. Sometimes you would need to work with complex types or dynamically typed data where the type information might not be readily available. In situations like these, TypeScri
7 min read
How enums works in TypeScript ? In this article, we will try to understand all the facts which are associated with enums in TypeScript. TypeScript enum: TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other da
4 min read
Enums in JavaScript Enums in JavaScript are used to define a set of named constants and make your code more readable and easier to understand. Instead of using random numbers or strings, enums give meaningful names to values, helping you avoid errors and improve maintainability. They're a simple way to group related va
4 min read