Lab 05: Enums & Literal Types

Objective

Use TypeScript enums (numeric, string, const), string literal unions, and discriminated union patterns for type-safe state machines.

Time

25 minutes

Prerequisites

  • Lab 01–04

Tools

  • Docker image: zchencow/innozverse-ts:latest


Lab Instructions

Step 1: Numeric Enums

enum Direction { North, South, East, West }  // 0, 1, 2, 3
enum HttpStatus {
    OK = 200, Created = 201, NoContent = 204,
    BadRequest = 400, Unauthorized = 401, NotFound = 404,
    InternalError = 500,
}

function describeStatus(code: HttpStatus): string {
    switch (code) {
        case HttpStatus.OK:            return "✅ Success";
        case HttpStatus.Created:       return "✅ Resource created";
        case HttpStatus.NotFound:      return "❌ Not found";
        case HttpStatus.InternalError: return "💥 Server error";
        default:                       return `HTTP ${code}`;
    }
}

console.log(describeStatus(HttpStatus.OK));
console.log(describeStatus(HttpStatus.NotFound));
console.log("Direction.North =", Direction.North);
console.log("Direction[0] =", Direction[0]);  // reverse mapping

💡 String enums (Red = 'RED') are more debuggable than numeric enums — the value appears in logs and serialized JSON. Numeric enums have reverse mapping (Direction[0] === 'North') but string enums do not. Prefer string enums for API contracts and serialized data.

📸 Verified Output:


Step 2: Const Enums & Literal Types

💡 const enum is inlined — the compiler replaces every Status.Active with "active" literally. No enum object exists at runtime. This gives the fastest possible code but breaks if the enum is in a separate file used by JavaScript (no const enum runtime). Use const enum for internal TypeScript-only code.

📸 Verified Output:


Step 3: Discriminated Unions as State Machines

💡 Extract<NetworkState, { state: 'loading' }> filters a union to only the variants matching a shape. It's the type-level equivalent of filter. Use it for factory functions that produce specific union variants, ensuring the return type precisely matches what you return.

📸 Verified Output:


Steps 4–8: Enum Utilities, Object Enums, Exhaustiveness, Flags, Capstone

📸 Verified Output:


Summary

Enums and literal types make TypeScript's type system practical for real-world modeling. You've covered numeric/string/const enums, string literal unions, discriminated unions as state machines, bit flags, and a Redux-style order state machine reducer.

Further Reading

Last updated