Open In App

TypeScript Enums Type

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:

Different types of the Enums:

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.






// 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 Example

Example 2: In this example, we will use the String enums to store a set of predefined string literals under a enum.






// 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 example

Conclusion: 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.


Article Tags :