TypeScript · module 9 of 21

Enums

Enums let you define a set of named constants, making code more readable and self-documenting.

Course map

What this module covers

4 steps · TypeScript

  1. Step 1. Enums

    Enums let you define a set of named constants, making code more readable and self-documenting. enum Status { Pending = "PENDING", Active = "ACTIVE", Inactive = "INACTIVE" } function checkRole(role: UserRole): void { if (role === UserRole.Admin) { console.log("Welcome, admin!"); } } Tips: prefer string enums for readability and debugging, use numeric enums only when you need automatic numbering, use const enums for performance when values are fixed, and enums work well in switch statements for exhaustive checks.

    String enums keep the same readability benefit as named constants, but unlike plain strings TypeScript will reject any value outside the enum. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [TypeScript] Add Left and Right members and declare a Direction variable.

  2. Step 2. Quiz: Enums

    Answer these questions about enums.

    String enums are generally preferred over numeric enums because their values are readable when debugging. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [TypeScript] Answer the quiz below.

  3. Step 3. Create and Use an Enum

    Create a string enum called Season with Spring/Summer/Autumn/Winter members. Declare a variable currentSeason of type Season.

    Four related constants are exactly the case enums exist for — a fixed, exhaustive, named set of options. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [TypeScript] Does Season have all four string members and is currentSeason typed as Season?

  4. Step 4. Mini project: Enums

    Create a string enum called Season with Spring/Summer/Autumn/Winter members. Declare a variable currentSeason of type Season. Turn the completed challenge into a small standalone project. Add realistic content, clear naming, one edge case or error state, and a short README-style explanation of how the main idea works.

    Four related constants are exactly the case enums exist for — a fixed, exhaustive, named set of options. This project stage asks you to apply the same idea without step-by-step scaffolding. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.

    Check yourself: [TypeScript] Does Season have all four string members and is currentSeason typed as Season?

Loading code lab...