TypeScript Union Types
TypeScript Union Types: Flexible Inputs and Safe Narrowing
A TypeScript union type (|) lets a variable or parameter accept more than one possible type, such as string | number. When a value has a union type, TypeScript only allows operations valid for every member until you narrow it down.
Discriminated unions take this a step further by pairing a shared literal tag (like kind or status) so switch statements narrow complex objects cleanly.
Narrowing Unions with typeof and Discriminated Tags
Use typeof for primitive unions and a shared status literal tag for object unions:
function formatId(id: string | number): string {
if (typeof id === "number") {
return `ID-${id.toString().padStart(4, "0")}`;
}
return id.trim().toUpperCase();
}
type FetchResult =
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; message: string };
function renderResult(res: FetchResult): string {
switch (res.status) {
case "loading":
return "Loading...";
case "success":
return `Loaded ${res.data.length} items`;
case "error":
return `Failed: ${res.message}`;
}
}
console.log(formatId(42), renderResult({ status: "success", data: ["a", "b"] }));
Common Mistakes to Avoid
- Calling
.toUpperCase()directly onstring | number: TypeScript rejects methods that do not exist onnumberuntil you narrow withtypeof val === "string". - Modeling state with booleans instead of discriminated unions: Using
{ loading: boolean; error?: string; data?: Item[] }allows impossible combinations (loading: trueanderrorset at once); discriminated unions make invalid states unrepresentable. - Confusing union
|with intersection&:A | Bmeans either A or B;A & Bmeans must have all properties of both A and B.
Frequently Asked Questions
How do I handle optional nullability with unions?
Write User | null or string | undefined, and narrow with if (user !== null) or optional chaining user?.name.
What is a string literal union?
A type like type Theme = "light" | "dark" | "system" restricts a string variable strictly to those exact values without the runtime weight of an enum.
How does TypeScript know res.data exists inside case "success":?
TypeScript tracks control flow on the shared status literal field and automatically narrows res to { status: "success"; data: string[] } inside that branch.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.