AceDevHub
Why TypeScript & Type BasicsFree

Unions and Literal Types

Model values that can be one of several types, pin exact string constants, and write exhaustive switch logic TypeScript can verify.

BeginnerFreeUnions

Real data is rarely one shape forever. API status is "pending" | "success" | "error". IDs may be string | number in legacy systems. Union types express "A or B" and force you to handle each case through narrowing or exhaustive switch. Literal types restrict to exact values — turning string into a finite set without runtime enum objects.

Unions are the foundation for result types, state machines, and configuration keys. Combined with control-flow analysis, they let the compiler prove you accessed the right fields in each branch — a compile-time substitute for defensive runtime checks scattered through JavaScript.

Union types and primitive narrowing

The pipe operator builds unions. Operations valid on all members work without narrowing; member-specific operations require proof first. typeof, in, and equality checks eliminate branches — the compiler tracks refinements across if, else, switch, return, and throw.

unions.ts
Loading editor…
Outputconsole
ABC-42
42

String literal unions

String literal unions model HTTP methods, roles, and UI states without TypeScript enum runtime overhead. Prefer unions plus as const over enum when values must match JSON strings from APIs.

literal-unions.ts
Loading editor…

Modeling API results

A fetch wrapper returning { ok: true, data: T } | { ok: false, error: string } prevents reading .data on error paths. This preview of discriminated unions becomes your default boundary pattern for internal services.

result-union.ts
Loading editor…
PatternExampleUse when
Primitive unionstring | numberFlexible IDs
Literal union"draft" | "published"Fixed states
Object union{ ok: true } | { ok: false }Result types

Exhaustiveness with never

When switch covers every union member, default can assign to never — if a new variant is added, tsc errors until you handle it. This is how large teams keep switch statements honest through refactors.

exhaustive.ts
Loading editor…
  • Unions express one-of — narrow before specific ops
  • Literal unions replace many enums
  • Result unions separate success and error
  1. 1| builds unions
  2. 2Narrow with typeof and equality
  3. 3assertNever for exhaustiveness
  4. 4Next chapter: functions and modeling