FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Advanced TypeScript Types

Generics, discriminated unions, conditional types, and infer type mechanics.

Freshness: current•14 min read•Software and Web Engineering

Key Learning Outcomes

  • ✓Master generic constraints and discriminated unions
  • ✓Implement infer conditional type extractions
Full Technical Reference Document

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.

Generic Type Parameter & Constraint
Discriminated Literal Tag Narrowing
Exhaustive never Branch Verification
Conditional infer Type Extraction
Zero-Overhead Erased JS Output
Conceptual teaching model synthesized from:typescript-54-spec,tc39-ecma262

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 ConstructSet-Theoretic RoleRuntime FootprintBest Engineering Application
Discriminated Union (kind: "a" | "b")Disjoint union of tagged member setsZero (plain JSON/JS literal property)Agent SSE events, React reducer states, API response envelopes
Exhaustive never HelperEmpty set proving all union members handledZero unless unreachable branch thrown at runtimeGuarantees compiler errors whenever a new union variant is added
satisfies Operator (TS 4.9+)Validates expression against schema while keeping narrow literal typesZeroTyped lookup tables, route config maps, token pricing tables
Conditional T extends U ? X : Y + inferType-level pattern matching over generics & tuplesZeroExtracting 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.

typescript
export 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 omitted
export function assertNever(value: never): never {
throw new Error(`Unhandled discriminated variant: ${JSON.stringify(value)}`);
}
​
// Conditional type inference extracting success payload cleanly
export 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 indexing
export 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 via assertNever; 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-cost type definitions, so reserve runtime schemas for API/storage boundaries and pure types internally.
  • Branded Nominal Types (type UserId = string & { readonly __brand: unique symbol }): Prevents accidentally swapping userId and workspaceId arguments at zero runtime cost, though requires explicit smart constructor helpers at system entry points.

Failure modes and misconceptions

  1. 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.
  2. Omitting default: return assertNever(x) in Switch Statements: Without an exhaustiveness check, adding a fifth { status: "cancelled" } variant compiles silently with undefined fallthroughs unless noImplicitReturns catches an explicit return gap.
  3. Abusing as T Type Assertions Instead of unknown + Narrowing: Writing res.data as MyResult forces the compiler to trust an unverified claim, hiding structural mismatches until customer runtime failures hit production. Use unknown plus validation or safe type guards.
  4. Over-Engineering Deep Recursive Type Gymnastics: Writing 15-level nested string-parsing SQL/route conditional types spikes CI tsc --noEmit memory and breaks editor IntelliSense. Prefer explicit helper interfaces or codegen when types exceed moderate nesting.
Reflect before revealing the guide

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 assertNever exhaustiveness checks.
  • Preserve exact literal keys alongside schema conformance using satisfies.
  • Write clean generic constraints and shallow infer conditional helpers without slowing tsc --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.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next