TypeScript Tutorial 0/102 lessons ~6 min read Lesson 38

    Discriminated Unions

    Represent state machines with explicit variants and exhaustive handling.

    Course progress0%
    Focus
    20 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Learning Objectives

    After completing this lesson, you will be able to:

    • Explain Discriminated Unions in terms of literal discriminants, control-flow narrowing, and never-based exhaustiveness.
    • Model enrollment workflows where loading, success, rejection, and failure carry different data without weakening the contract to any.
    • Trace what the compiler checks and what JavaScript remains at runtime.
    • Recognize and correct this recurring failure mode: using optional fields in one broad interface and permitting impossible combinations.
    • Defend when to use Discriminated Unions and when a simpler design is clearer.
    • Distinguish the compile-time guarantees of Discriminated Unions from runtime behavior.
    • Read and explain compiler diagnostics related to Discriminated Unions.
    • Choose a simpler alternative when Discriminated Unions would add unnecessary complexity.
    • Apply Discriminated Unions without weakening untrusted input to any.
    • Review Discriminated Unions for maintainability in a multi-team codebase.
    • Test both accepted and intentionally rejected type scenarios.
    • Identify the trust boundaries around code that uses Discriminated Unions.
    • Evaluate checker, build, bundle, and runtime costs separately.
    • Explain the security limitations of erased TypeScript types.
    • Use Discriminated Unions in a production-oriented TechLearningPro design.

    Introduction

    A growing TechLearningPro codebase must support enrollment workflows where loading, success, rejection, and failure carry different data. Copying loosely related types makes valid changes expensive and lets assumptions drift between the UI, application services, and API adapters. The team needs a design that expresses the relationship explicitly while remaining understandable to reviewers.

    This lesson approaches Discriminated Unions as an engineering decision rather than syntax to memorize. You will connect the developer experience to the TypeScript compiler, emitted JavaScript, production boundaries, and the maintenance costs paid by a team over time.

    What Is This Concept?

    In simple language: A discriminated union gives each variant a shared literal tag that identifies its valid fields.

    Professional explanation: Discriminated Unions is a compile-time modeling technique based on literal discriminants, control-flow narrowing, and never-based exhaustiveness. It lets the checker preserve domain relationships, reject inconsistent programs, and communicate intent without claiming that a TypeScript type validates values at runtime.

    Why Do We Need It?

    Without Discriminated Unions
            │
            ▼
    Ambiguous intent and defects discovered late
            │
            ▼
    TypeScript models the contract
            │
            ▼
    Earlier feedback, safer change, clearer design
    • It makes the relationship behind enrollment workflows where loading, success, rejection, and failure carry different data visible in the program.
    • It moves many integration mistakes into editor and CI feedback.
    • It reduces duplicated contracts that can drift during refactoring.
    • It gives maintainers a precise vocabulary for reviewing design changes.
    • It supports the key engineering decision: encode mutually exclusive domain states explicitly even when a flat interface looks shorter.

    Real-World Analogy

    A passport's document type determines which fields are valid and which processing lane it enters.

    How It Works

    Compile time

    The checker applies literal discriminants, control-flow narrowing, and never-based exhaustiveness, resolves the resulting relationships, and reports assignments or operations that violate them. These checks happen during editing or compilation and are erased from ordinary JavaScript output.

    Runtime

    At runtime, Discriminated Unions has no independent type-level behavior: emitted JavaScript follows ordinary JavaScript semantics. External data still requires runtime validation.

    Critical boundary: TypeScript types are erased before execution. A successful type check does not validate JSON, environment variables, form data, database rows, or messages received from another process. Validate untrusted values at runtime, then narrow them into trusted domain types.
    1. 1. Identify the invariant in the requirement: enrollment workflows where loading, success, rejection, and failure carry different data.
    2. 2. Represent only the information the compiler needs to preserve that invariant.
    3. 3. Apply literal discriminants, control-flow narrowing, and never-based exhaustiveness and inspect inference rather than guessing it.
    4. 4. Compile under strict mode and test both accepted and rejected calls.
    5. 5. Inspect emitted JavaScript when runtime behavior matters.
    6. 6. Validate unknown input before it enters the trusted typed core.

    Architecture / Flow Diagram

    Domain requirement: enrollment workflows where loading, success, rejection, and failure carry different data
            │
            ▼
    Type model: Discriminated Unions
            │  compiler applies literal discriminants, control-flow narrowing, and never-based exhaustiveness
            ▼
    Accepted program ──or── precise diagnostic
            │
            ▼
    Emitted JavaScript (types erased)
            │
            ▼
    Runtime validation at every untrusted boundary

    Code Examples

    Basic Example: Smallest useful model

    This isolates the essential behavior of Discriminated Unions.

    ts
    type Result = { kind: "ok"; value: string } | { kind: "error"; message: string };

    Intermediate Example: Application boundary

    This applies the idea to enrollment workflows where loading, success, rejection, and failure carry different data.

    ts
    type Enrollment =
    | { status: "pending"; requestedAt: Date }
    | { status: "active"; enrolledAt: Date }
    | { status: "rejected"; reason: string };

    Advanced Example: Production-oriented design

    This version makes the trade-off—encode mutually exclusive domain states explicitly even when a flat interface looks shorter—explicit.

    ts
    function assertNever(value: never): never { throw new Error("Unexpected variant"); }
    function label(state: Enrollment): string {
    switch (state.status) {
    case "pending": return "Awaiting review";
    case "active": return state.enrolledAt.toISOString();
    case "rejected": return state.reason;
    default: return assertNever(state);
    }
    }

    Enterprise Example

    TechLearningPro uses Discriminated Unions while implementing enrollment workflows where loading, success, rejection, and failure carry different data. A boundary adapter first validates HTTP or queue payloads as unknown. The application layer then relies on the static contract, and the domain layer stays independent of transport details. Reviewers can distinguish a compile-time guarantee from authorization, validation, and other runtime controls.

    Student
       │
       ▼
    React / Angular UI
       │ typed command
       ▼
    Application service
       │ validated DTO
       ▼
    API client ─────► Runtime schema at trust boundary
       │
       ▼
    Backend API

    Deep Dive

    literal discriminants, control-flow narrowing, and never-based exhaustiveness is useful because it preserves a relationship rather than merely replacing a long annotation with a short name. If no meaningful relationship is being enforced, the abstraction may be ceremony.

    The principal design risk is using optional fields in one broad interface and permitting impossible combinations. A strong design keeps diagnostics readable, exposes a small public surface, and documents the invariant in domain language.

    Discriminated Unions should end at a trust boundary. Parsed JSON, storage records, environment variables, and third-party SDK values begin as unknown; validation creates runtime evidence before a typed domain value is constructed.

    The governing trade-off is encode mutually exclusive domain states explicitly even when a flat interface looks shorter. Prefer the least powerful construct that keeps invalid states unrepresentable and remains easy for another engineer to modify.

    Common Mistakes

    For each mistake, identify the false assumption and replace it with an explicit contract:

    1. 1. Treating Discriminated Unions as runtime validation; types are erased and hostile input is unchanged.
    2. 2. Using any to silence a failure instead of understanding literal discriminants, control-flow narrowing, and never-based exhaustiveness.
    3. 3. Ignoring the central pitfall: using optional fields in one broad interface and permitting impossible combinations.
    4. 4. Adding assertions before proving the asserted fact.
    5. 5. Designing from implementation shapes instead of domain invariants.
    6. 6. Publishing an abstraction whose diagnostics are harder than the duplicated code.
    7. 7. Testing only successful examples and never adding compile-time negative cases.
    8. 8. Coupling domain contracts to a framework, transport, or generated client unnecessarily.
    9. 9. Assuming a more sophisticated type improves runtime speed; it does not.

    Best Practices

    • Enable strict mode and keep strictNullChecks on.
    • Start with a concrete domain example before extracting an abstraction.
    • Name the invariant behind enrollment workflows where loading, success, rejection, and failure carry different data.
    • Document why literal discriminants, control-flow narrowing, and never-based exhaustiveness is necessary.
    • Prefer unknown to any at untrusted boundaries.
    • Validate external values with runtime code or a schema library.
    • Keep public contracts smaller than private implementation types.
    • Let inference handle local details; annotate exported boundaries.
    • Use type tests for both expected success and expected failure.
    • Keep compiler diagnostics understandable to the consuming team.
    • Avoid assertions unless runtime evidence or construction proves them.
    • Inspect generated declarations for library-facing APIs.
    • Measure checker latency before blaming an advanced construct.
    • Separate domain types from wire-format DTOs.
    • Review optionality, mutability, and nullability deliberately.
    • Revisit the decision periodically: encode mutually exclusive domain states explicitly even when a flat interface looks shorter.

    Performance

    Type annotations normally have no direct runtime cost because they are removed from emitted JavaScript. Performance work must separate editor/type-checking cost, compilation cost, bundle output, and actual JavaScript execution.

    • Discriminated Unions normally changes checker work, not JavaScript execution speed.
    • Deep composition can increase editor and CI type-checking time; measure with compiler diagnostics before simplifying.
    • Runtime performance depends on emitted algorithms, allocations, I/O, and validation—not on erased annotations.
    • Type-driven refactoring may enable better code, but benchmark the emitted application rather than claiming a type-level speedup.

    Security

    Static types improve reviewability and make invalid internal states harder to express, but they are not a security boundary. Attackers interact with the emitted JavaScript and network interfaces, not your type declarations.

    • Parse untrusted input as unknown and validate structure, ranges, formats, and size at runtime.
    • Keep authentication and authorization checks in executable code.
    • Do not let an assertion convert attacker-controlled data into a trusted domain value.
    • Avoid exposing sensitive fields merely because a projected type hides them; the runtime object may still contain them.
    • Use Discriminated Unions to improve reviewability, while treating validation and policy enforcement as separate controls.

    Real-World Architecture

    Place Discriminated Unions in the narrowest stable layer that owns its invariant. Transport adapters validate data and map DTOs; application services coordinate use cases; domain modules expose purposeful contracts; infrastructure implements those contracts. This direction prevents a clever type from becoming an accidental dependency shared by every layer.

    Interview Questions & Answers

    Beginner

    1What problem does Discriminated Unions solve?+
    It models enrollment workflows where loading, success, rejection, and failure carry different data by using literal discriminants, control-flow narrowing, and never-based exhaustiveness. The value is earlier, clearer feedback about inconsistent code; it is not runtime validation.
    2Does Discriminated Unions exist at runtime?+
    Its type information does not. The compiler erases types, although JavaScript constructs such as classes or imports may emit runtime code. Therefore external data must still be checked.
    3What JavaScript remains after the types used by Discriminated Unions are erased?+
    Only the executable JavaScript constructs remain. Type aliases, interfaces, annotations, and most type operators do not become runtime checks. Inspecting emitted output is the reliable way to answer this for a specific compiler configuration.
    4How should a developer read an error related to Discriminated Unions?+
    Start from the first incompatible relationship, identify the expected and actual types, and trace where each was inferred. Avoid immediately adding an assertion because that removes evidence without correcting the model.
    5When is unknown safer than any in this lesson?+
    Unknown is safer whenever a value has not yet been proven, especially at network, storage, environment, or user-input boundaries. It requires validation or narrowing before use; any suppresses that review point.

    Intermediate

    1How would you test this type-level design?+
    Add positive examples that must compile and negative examples marked with @ts-expect-error. Also test emitted runtime behavior separately, because a type test cannot prove validation or authorization.
    2What is the most common design error with Discriminated Unions?+
    using optional fields in one broad interface and permitting impossible combinations. It fails because the abstraction stops expressing the real invariant and either accepts invalid states or becomes too difficult to use.
    3How would you add a negative type test for Discriminated Unions?+
    Write a small call or assignment that must be rejected and use the repository's type-test convention, such as @ts-expect-error with a reason. CI then fails if a future change unexpectedly makes the unsafe case valid.
    4Where should annotations be explicit and where should inference lead?+
    Annotate exported APIs, domain boundaries, callbacks with contextual ambiguity, and long-lived public contracts. Prefer inference for local implementation details so types stay precise and refactors do not duplicate information.
    5How do runtime schemas cooperate with Discriminated Unions?+
    A schema checks unknown data while the program is running and returns evidence or an error. After successful parsing, TypeScript can safely carry the inferred domain type through trusted internal code.

    Senior

    1When should you replace this design with something simpler?+
    Replace it when encode mutually exclusive domain states explicitly even when a flat interface looks shorter favors clarity: if there is no relationship to preserve, consumers cannot understand diagnostics, or duplication is cheaper than abstraction, concrete types are the safer engineering choice.
    2How do you introduce this into an existing enterprise codebase?+
    Begin at one stable boundary, preserve compatibility, add type tests, and migrate callers incrementally. Keep runtime behavior unchanged unless separately specified and validate boundary data before constructing trusted values.
    3How would you keep Discriminated Unions from leaking across architectural layers?+
    Place the contract in the layer that owns the invariant, map wire DTOs at adapters, and expose narrow application or domain interfaces. Framework and generated-client types should not become the universal domain vocabulary.
    4What metrics would you inspect before optimizing this type design?+
    Measure editor latency, tsc extended diagnostics, incremental build time, declaration generation, and affected-project scope. Separately profile bundle size and runtime behavior because erased type complexity is not runtime CPU cost.
    5When should a team simplify its use of Discriminated Unions?+
    Simplify when diagnostics become opaque, checker cost is measurable, the abstraction has few consumers, or maintainers cannot state the invariant it protects. Preserve domain safety while reducing type-level cleverness.

    Architect

    1Where should ownership of this contract live?+
    The layer that owns the business invariant should own the contract. Adapters may translate it, but frameworks and generated clients should not define the domain vocabulary because their change cadence is different.
    2How do you evaluate its organization-wide value?+
    Track defect classes, API misuse, refactoring effort, declaration quality, onboarding friction, and checker latency. A sophisticated type is justified only when the prevented ambiguity outweighs learning and maintenance cost.
    3How would you govern Discriminated Unions across a monorepo?+
    Define ownership and public entry points, publish small declaration surfaces, enforce dependency direction, add type and runtime contract tests, version shared contracts, and measure build impact through project references or affected builds.
    4What is the migration strategy if teams currently rely on any?+
    Inventory escape hatches by risk, start at external boundaries with unknown plus schemas, enable strict options incrementally, add typed facades around legacy modules, and prevent new any usage while paying down existing hotspots.
    5How do security and maintainability trade-offs affect this design?+
    Richer static contracts can prevent accidental misuse and clarify review, but they cannot enforce authorization or sanitize hostile values. Architects balance readable types, executable validation, policy enforcement, ownership, and operational observability.

    Practical Exercise

    Problem: Design an exhaustive enrollment state machine and render every state.

    Difficulty: Advanced

    Requirements

    • Use Discriminated Unions to encode the central relationship without any.
    • Accept boundary input as unknown and include a minimal runtime validation step.
    • Add one valid and two intentionally rejected compile-time examples.
    • Explain the emitted JavaScript behavior and one design trade-off.

    Expected behavior: The valid path compiles and runs, invalid type combinations fail during checking, malformed external input is rejected by executable validation, and the design remains readable under strict mode.

    Hints

    • Write the invariant in one sentence before writing a type.
    • Begin with the smallest operation that demonstrates literal discriminants, control-flow narrowing, and never-based exhaustiveness.
    • Use satisfies or @ts-expect-error where a type test is clearer than an assertion.

    The complete solution is intentionally withheld. First model the contract, compile under strict mode, and explain every assertion or escape hatch during review.

    Key Takeaways

    • Discriminated Unions addresses enrollment workflows where loading, success, rejection, and failure carry different data.
    • Its core mechanism is literal discriminants, control-flow narrowing, and never-based exhaustiveness.
    • Its guarantees are compile-time guarantees.
    • Emitted JavaScript still determines runtime behavior.
    • Unknown external values require runtime validation.
    • The main hazard is using optional fields in one broad interface and permitting impossible combinations.
    • The key trade-off is encode mutually exclusive domain states explicitly even when a flat interface looks shorter.
    • Strict mode and negative type tests make the contract more reliable.
    • Small public surfaces improve diagnostics and maintainability.
    • Type sophistication is valuable only when it preserves a real invariant.
    • Security controls and performance claims require runtime evidence.

    Summary

    Discriminated Unions gives TechLearningPro a precise way to model enrollment workflows where loading, success, rejection, and failure carry different data through literal discriminants, control-flow narrowing, and never-based exhaustiveness. Used with strict checking, boundary validation, and deliberate ownership, it improves change safety without pretending that erased types enforce runtime policy.

    Next Lesson Preview

    Next, study Narrowing and Type Guards. The next lesson extends this foundation with another production modeling technique.

    Ready to mark this lesson complete?Track your journey across the entire course.