TypeScript Union Types and Runtime Narrowing
Design safe API result types, reject untrusted data at runtime, and remove unsafe assertions from an error-handling flow.
Key Learning Objectives
- Model successful and failed results as a discriminated union.
- Narrow a union by checking its tag.
- Explain why unknown differs from any.
- Test malformed API data.
Model all meaningful states explicitly
An API can succeed or fail. Instead of returning an object with optional data and error fields that can contradict each other, use a union in which each variant has a distinguishing tag. The compiler then prevents reading data when the result is an error. This is a design technique: start by listing the valid states of your feature, then encode only those states in your type.
Narrow before accessing properties
Checking the kind field lets TypeScript narrow the union to one branch. The compiler checks your source code; it does not validate unknown JSON arriving over a network. Parse and validate untrusted inputs before treating them as an application type. Prefer unknown when you genuinely lack type information because it forces a useful runtime check.
type Result = { kind: "ok"; value: number } | { kind: "error"; message: string };
function describe(result: Result): string {
return result.kind === "ok" ? `Score: ${result.value}` : result.message;
}
function isRecord(x: unknown): x is Record<string, unknown> {
return typeof x === "object" && x !== null && !Array.isArray(x);
}
The tag check narrows Result; the separate type guard is a runtime check for untrusted input.
Use exhaustive switches for future changes
When a union gains a third variant, an exhaustive switch with a never check can make the compiler point out forgotten handling branches. Avoid replacing uncertainty with as SomeType assertions everywhere; assertions silence a warning but do not transform a bad value into a good one. Write a malformed-response test to prove your parsing boundary works.
Build It: Typed API response inspector
Build a parser that accepts unknown input and returns either a validated score or a specific error.
Project Deliverables
- Result type with two distinct variants.
- A validator for score bounds and types.
- A display function with exhaustive handling.
Acceptance Criteria
- Reject a missing score.
- Reject score as a string.
- Accept score 0 and score 100.
Next Steps & Related Learning
This interactive lesson is part of the TypeScript curriculum. Continue exploring or try another interactive lesson: