Lesson 42 of 60 – Enums
70%

Enums in TypeScript

An enum, short for enumeration, is a TypeScript feature used to define a set of named constants. Enums are useful when a variable should contain one value from a predefined collection of values.

Note: Enums make related constant values easier to organize and understand.

1. What is an Enum?

An enum allows you to create a collection of named values.

enum Direction {
    Up,
    Down,
    Left,
    Right
}

Here, Direction is an enum containing four values.

2. Why Use Enums?

Enums are useful when a variable should have one value from a fixed set of choices.

enum Status {
    Pending,
    Approved,
    Rejected
}

This makes the possible values clear in the program.

3. Creating a Numeric Enum

By default, TypeScript assigns numeric values to enum members.

enum Color {
    Red,
    Green,
    Blue
}

console.log(Color.Red);
console.log(Color.Green);
console.log(Color.Blue);

The default values start from 0.

4. Default Numeric Values

enum Color {
    Red,
    Green,
    Blue
}

console.log(Color.Red);   // 0
console.log(Color.Green); // 1
console.log(Color.Blue);  // 2

When no value is specified, TypeScript automatically increments the previous numeric value.

5. Starting an Enum with a Custom Number

You can specify the starting numeric value.

enum Status {
    Pending = 1,
    Approved,
    Rejected
}

console.log(Status.Pending);  // 1
console.log(Status.Approved); // 2
console.log(Status.Rejected); // 3

6. Assigning Different Numeric Values

Each enum member can have its own numeric value.

enum Status {
    Pending = 10,
    Approved = 20,
    Rejected = 30
}

This is useful when specific numeric values have a particular meaning.

7. String Enums

Enum members can also have string values.

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT"
}

String enums are often easier to understand when debugging or working with external data.

8. Accessing Enum Values

enum Direction {
    Up = "UP",
    Down = "DOWN"
}

console.log(Direction.Up);
console.log(Direction.Down);

Use the enum name followed by the member name to access an enum value.

9. Assigning an Enum to a Variable

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let direction: Direction =
    Direction.Up;

console.log(direction);

The variable can be typed using the enum name.

10. Enum in Function Parameters

enum Status {
    Pending,
    Approved,
    Rejected
}

function showStatus(
    status: Status
) {

    console.log(status);

}

showStatus(Status.Approved);

The function parameter accepts values from the Status enum.

11. Enum with if Statement

enum Status {
    Pending,
    Approved,
    Rejected
}

let status: Status =
    Status.Approved;

if (status === Status.Approved) {

    console.log(
        "Application approved"
    );

}

12. Enum with switch

enum Status {
    Pending,
    Approved,
    Rejected
}

function checkStatus(
    status: Status
) {

    switch (status) {

        case Status.Pending:
            console.log("Pending");
            break;

        case Status.Approved:
            console.log("Approved");
            break;

        case Status.Rejected:
            console.log("Rejected");
            break;

    }

}

13. Enum for Days

Enums can represent a fixed list of days.

enum Day {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

let today: Day =
    Day.Monday;

console.log(today);

14. Enum for User Roles

enum Role {
    Admin,
    Teacher,
    Student
}

let userRole: Role =
    Role.Student;

console.log(userRole);

This is useful for applications that have predefined user roles.

15. Enum with an Interface

enum Role {
    Admin,
    Student
}

interface User {
    name: string;
    role: Role;
}

const user: User = {
    name: "Amit",
    role: Role.Student
};

console.log(user);

An enum can be used as the type of an interface property.

16. String Enum with Interface

enum Role {
    Admin = "ADMIN",
    Student = "STUDENT"
}

interface User {
    name: string;
    role: Role;
}

const user: User = {
    name: "Amit",
    role: Role.Student
};

17. Enum Members as Constants

Enum members can represent fixed constant values.

enum PaymentStatus {
    Pending = "PENDING",
    Paid = "PAID",
    Failed = "FAILED"
}

let payment: PaymentStatus =
    PaymentStatus.Paid;

console.log(payment);

18. Enum for Order Status

enum OrderStatus {
    Placed = "PLACED",
    Shipped = "SHIPPED",
    Delivered = "DELIVERED",
    Cancelled = "CANCELLED"
}

function showOrderStatus(
    status: OrderStatus
) {

    console.log(
        "Order:",
        status
    );

}

showOrderStatus(
    OrderStatus.Shipped
);

19. Reverse Mapping in Numeric Enums

Numeric enums support reverse mapping.

enum Color {
    Red,
    Green,
    Blue
}

console.log(Color.Red);
console.log(Color[0]);

Numeric enum values can be used to retrieve their corresponding member names.

20. String Enums and Reverse Mapping

String enums do not provide the same numeric reverse mapping behavior.

enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE"
}

console.log(Color.Red);

String enum values are accessed directly through their named members.

21. const Enum

A const enum is a special enum declaration designed for efficient generated JavaScript.

const enum Direction {
    Up,
    Down,
    Left,
    Right
}

let direction =
    Direction.Up;

console.log(direction);

22. Enum with React Components

enum Theme {
    Light = "light",
    Dark = "dark"
}

type Props = {
    theme: Theme;
};

function ThemeDisplay(
    { theme }: Props
) {

    return (
        <div>
            Current Theme: {theme}
        </div>
    );

}

Enums can be used to restrict component properties to predefined values.

23. Enum with React Native

enum ButtonType {
    Primary = "primary",
    Secondary = "secondary"
}

type ButtonProps = {
    type: ButtonType;
};

function AppButton(
    { type }: ButtonProps
) {

    return (
        <Button
            title={type}
            onPress={() => {}}
        />
    );

}

Enums can help define fixed options for React Native component properties.

24. Enum with API Data

enum ApiStatus {
    Success = "success",
    Error = "error",
    Loading = "loading"
}

function showStatus(
    status: ApiStatus
) {

    if (
        status === ApiStatus.Success
    ) {

        console.log("Data loaded");

    } else if (
        status === ApiStatus.Error
    ) {

        console.log("Error occurred");

    } else {

        console.log("Loading");

    }

}

25. Enum with Function Return Type

enum Status {
    Pending,
    Approved,
    Rejected
}

function getStatus(): Status {

    return Status.Approved;

}

const result =
    getStatus();

console.log(result);

26. Enum vs Union Type

A union type can also represent a fixed set of values.

type Status =
    "pending" |
    "approved" |
    "rejected";

let status: Status =
    "approved";

An enum creates named members, while a union of literals directly represents allowed values.

27. Choosing Meaningful Enum Names

Use clear names for enums and their members.

enum PaymentStatus {
    Pending,
    Paid,
    Failed
}

Meaningful names make the code easier to understand and maintain.

28. Common Enum Mistakes

  • Using unclear enum names.
  • Using numeric values without understanding their meaning.
  • Mixing unrelated values in one enum.
  • Using an enum when a simple union type is enough.
  • Assuming string enums support numeric reverse mapping.
  • Using duplicate values without a clear reason.

29. Complete Practical Example

enum StudentStatus {
    Active = "ACTIVE",
    Inactive = "INACTIVE",
    Completed = "COMPLETED"
}

interface Student {
    name: string;
    course: string;
    status: StudentStatus;
}

function showStudent(
    student: Student
) {

    console.log(
        "Name:",
        student.name
    );

    console.log(
        "Course:",
        student.course
    );

    switch (student.status) {

        case StudentStatus.Active:
            console.log("Student is active");
            break;

        case StudentStatus.Inactive:
            console.log("Student is inactive");
            break;

        case StudentStatus.Completed:
            console.log("Course completed");
            break;

    }

}

const student: Student = {
    name: "Amit",
    course: "React Native",
    status: StudentStatus.Active
};

showStudent(student);

30. Enums Summary

Enums provide a convenient way to define named constants and represent a fixed collection of related values.

enum UserRole {
    Admin = "ADMIN",
    Teacher = "TEACHER",
    Student = "STUDENT"
}

let role: UserRole =
    UserRole.Student;

console.log(role);

Enums can be used with variables, functions, interfaces, React components, and React Native applications.

📌 Key Points

  • Enums define a set of named constants.
  • Numeric enums use numbers by default.
  • Numeric enums normally start from 0.
  • You can specify custom numeric values.
  • String enums use explicit string values.
  • Enums can be used as variable types.
  • Enums can be used in function parameters and return types.
  • Enums can be used with interfaces.
  • Enums are useful for fixed application states and roles.
  • Enums can be used in React and React Native applications.
  • Numeric enums support reverse mapping.
  • String enums do not provide numeric reverse mapping.
  • const enum is a special enum form.
  • Union types can sometimes be used instead of enums.

🧠 Quick Quiz

Question: Which keyword is used to create an enumeration in TypeScript?