Mental model
TypeScript's type system is structural, set-theoretic, and completely erased during emit: a type names a set of shapes rather than a nominal runtime class hierarchy, where unknown is the universal top set (safe for untrusted inputs), never is the uninhabited empty set (ideal for proving switch exhaustiveness), and any is an unsafe escape hatch that turns off type checking altogether. Modeling application state with discriminated unions ("making illegal states unrepresentable") paired with bounded generics, satisfies, and shallow infer conditional utilities catches mismatched API contracts, unhandled SSE event variants, and stale state machines cleanly at tsc --noEmit.
Theory
Replacing loose "flag bag" interfaces ({ loading: boolean; data?: T; error?: string }—which permits { loading: true, error: "fail", data: ... }!) with a discriminated union keyed by a literal tag (status or kind) turns runtime ambiguity into compiler-verified exhaustive branching.
| TypeScript Construct | Set-Theoretic Role | Runtime Footprint | Best Engineering Application |
|---|---|---|---|
Discriminated Union (kind: "a" | "b") | Disjoint union of tagged member sets | Zero (plain JSON/JS literal property) | Agent SSE events, React reducer states, API response envelopes |
Exhaustive never Helper | Empty set proving all union members handled | Zero unless unreachable branch thrown at runtime | Guarantees compiler errors whenever a new union variant is added |
satisfies Operator (TS 4.9+) | Validates expression against schema while keeping narrow literal types | Zero | Typed lookup tables, route config maps, token pricing tables |
Conditional T extends U ? X : Y + infer | Type-level pattern matching over generics & tuples | Zero | Extracting ReturnType, async payload shapes, event handler args |
Distributive Conditionals, satisfies, and Compiler Check Performance
A frequently misunderstood property of conditional types is distributivity over naked type parameters: given type Box<T> = T extends any ? T[] : never, passing Box<string | number> distributes cleanly into string[] | number[] (not (string | number)[]!). Wrapping both sides in single-element tuples ([T] extends [any]) suppresses distribution intentionally whenever you want whole-union evaluation. Equally valuable in configuration objects is satisfies: unlike const ROUTES: Record<string, RouteConfig> = ..., which widens keys back to arbitrary string, const ROUTES = { ... } satisfies Record<string, RouteConfig> validates every entry and keeps autocomplete locked to the exact literal keys. Keep recursive conditional types shallow (depth <= 4–5), however, because runaway template-literal or nested mapped-conditional types degrade tsc IDE responsiveness drastically.
typescriptexport type ToolExecutionState<TOutput> =| { status: "idle" }| { status: "running"; startedAt: number }| { status: "succeeded"; output: TOutput; latencyMs: number }| { status: "failed"; errorCode: string; retryable: boolean };// Exhaustiveness invariant helper: fails tsc if any status branch is omittedexport function assertNever(value: never): never {throw new Error(`Unhandled discriminated variant: ${JSON.stringify(value)}`);}// Conditional type inference extracting success payload cleanlyexport type ExtractSucceededOutput<T> = T extends { status: "succeeded"; output: infer O } ? O : never;export function renderExecutionBadge<T>(state: ToolExecutionState<T>): string {switch (state.status) {case "idle":return "Queued";case "running":return `Running since ${state.startedAt}`;case "succeeded":return `Done in ${state.latencyMs}ms`;case "failed":return state.retryable ? `Retrying (${state.errorCode})` : `Failed (${state.errorCode})`;default:return assertNever(state);}}// `satisfies` checks schema shape while preserving literal keys for indexingexport const MODEL_TIERS = {fast: { maxTokens: 8192, costMultiplier: 1 },reasoning: { maxTokens: 32768, costMultiplier: 4 },} as const satisfies Record<string, { maxTokens: number; costMultiplier: number }>;
Alternatives and trade-offs
- Pure TypeScript Discriminated Unions +
satisfies: Zero bundle cost, instantaneous inference across React components and route handlers, strict exhaustiveness viaassertNever; types disappear after compilation so external boundaries still need runtime validation. - Schema-First Inference (
z.infer<typeof Schema>in Zod / Valibot): Single source of truth generating both runtime JSON validation and static TypeScript union types; adds small client bundle bytes (~3–14 KB) compared to zero-costtypedefinitions, so reserve runtime schemas for API/storage boundaries and pure types internally. - Branded Nominal Types (
type UserId = string & { readonly __brand: unique symbol }): Prevents accidentally swappinguserIdandworkspaceIdarguments at zero runtime cost, though requires explicit smart constructor helpers at system entry points.
Failure modes and misconceptions
- Modeling Mutual Exclusion with Optional Bags (
{ data?: T; error?: E }): Forces null checks everywhere and allows contradictory{ data, error }states. Convert state bags directly into discriminated unions. - Omitting
default: return assertNever(x)in Switch Statements: Without an exhaustiveness check, adding a fifth{ status: "cancelled" }variant compiles silently withundefinedfallthroughs unlessnoImplicitReturnscatches an explicit return gap. - Abusing
as TType Assertions Instead ofunknown+ Narrowing: Writingres.data as MyResultforces the compiler to trust an unverified claim, hiding structural mismatches until customer runtime failures hit production. Useunknownplus validation or safe type guards. - Over-Engineering Deep Recursive Type Gymnastics: Writing 15-level nested string-parsing SQL/route conditional types spikes CI
tsc --noEmitmemory and breaks editor IntelliSense. Prefer explicit helper interfaces or codegen when types exceed moderate nesting.
Decision scenario
Your streaming AI agent workbench handles 7 server-sent event payloads (delta, tool_start, tool_result, citation, usage, error, done) rendered across React cards and persisted in client state reducers. Model the event contract once as a tagged discriminated union keyed on type, derive helper extractor types via shallow infer (EventOfType<K>), enforce assertNever(event) inside every reducer switch so adding an 8th event forces explicit UI handling across all components, validate incoming wire frames with Zod/Valibot at the EventSource boundary, and lock model/tier routing tables with satisfies so invalid tier keys fail compile checks without losing literal autocomplete.
Learning outcomes
- Contrast structural set-theoretic typing (
unknown,never,any) against nominal class hierarchies. - Replace ambiguous optional-property interfaces cleanly with discriminated unions and
assertNeverexhaustiveness checks. - Preserve exact literal keys alongside schema conformance using
satisfies. - Write clean generic constraints and shallow
inferconditional helpers without slowingtsc --noEmit.
Trade-offs
Mastering discriminated unions, satisfies, and bounded conditional inference yields self-documenting, compiler-verified API and UI state transitions with zero emitted JS overhead, balanced against strict schema checks at runtime network edges and restraint against deeply nested type complexity.