Lesson 2 of 4 · 11 min · TypeScript fundamentals
Union types, narrowing and discriminated unions
What you will learn
- Union (
|) and intersection (&) types - Narrowing with
typeof,instanceof,in, truthiness and equality - Write custom type guards with
is - Model data with discriminated unions and check cases exhaustively with
never - Avoid impossible states in UI and API types
In simple words
Real data is often "one of several things": an id might be a number or a string, an API response is either a success with data or a failure with an error. A union type says exactly that, "this or that". Narrowing is TypeScript following your if checks: once you have checked that a value is a string, it lets you use string methods inside the if. Together they make code safe without being wordy.
Words to know
- Union type: a type that can be one of several types, written
A | B. - Narrowing: TypeScript refining a broad type to a more specific one after a check.
- Type guard: a check (or function) that tells TypeScript which type a value has.
- Discriminated union: a union whose members share a field with a unique literal value that tells them apart.
Union types
type Id = number | string;
function show(id: Id) {
console.log(id.toUpperCase()); // Error: Property 'toUpperCase' does not exist on type 'number'
}
You may only use what is valid for every member of the union until you narrow it. Unions of literals work like enums:
type Status = "paid" | "pending" | "refunded";
type Size = 1 | 2 | 3;
let status: Status = "paid";
status = "shipped"; // Error
Common use: string | null (a value that may be missing), Order | undefined (the result of find), number | "all".
Narrowing
TypeScript tracks your checks, called control-flow analysis:
function show(id: number | string) {
if (typeof id === "string") {
id.toUpperCase(); // id: string here
} else {
id.toFixed(2); // id: number here
}
}
The main narrowing tools:
| Check | Narrows |
|---|---|
typeof x === "string" (also "number", "boolean", "function", "object", "undefined") |
primitives |
x === null, x == null, x === undefined |
removes null and undefined |
truthiness: if (x) |
removes null, undefined, 0, "" (careful: 0 and "" are removed too) |
x instanceof Date |
classes |
"email" in obj |
objects with a given property |
Array.isArray(x) |
arrays |
x === "paid" |
literal types |
switch on a literal |
each case |
function format(value: string | string[] | null) {
if (value === null) return "none";
if (Array.isArray(value)) return value.join(", "); // value: string[]
return value.trim(); // value: string
}
function area(shape: Circle | Rectangle) {
if ("radius" in shape) return Math.PI * shape.radius ** 2; // Circle
return shape.width * shape.height; // Rectangle
}
Narrowing also works with early returns (as above), && chains, optional chaining and assignments. After a narrowing check, TypeScript remembers the result within that scope, but not across function calls or after reassignment inside callbacks.
Custom type guards
When built-in checks are not enough, write a function whose return type is a type predicate (x is Type):
interface Order { id: number; amount: number }
function isOrder(value: unknown): value is Order {
return (
typeof value === "object" && value !== null &&
typeof (value as Record<string, unknown>).id === "number" &&
typeof (value as Record<string, unknown>).amount === "number"
);
}
const data: unknown = JSON.parse(text);
if (isOrder(data)) {
console.log(data.amount.toFixed(2)); // data: Order
}
A type guard is a promise you must keep: if your check is wrong, TypeScript trusts it anyway. For real API data, prefer a schema validation library (such as Zod, Valibot or ArkType) that validates at run time and infers the TypeScript type from the schema, so the check and the type cannot drift apart:
import { z } from "zod";
const OrderSchema = z.object({ id: z.number(), amount: z.number(), status: z.enum(["paid", "pending"]) });
type Order = z.infer<typeof OrderSchema>;
const order = OrderSchema.parse(await response.json()); // throws if the data is wrong
Assertion functions (asserts x is T) are similar but throw instead of returning a boolean.
Intersection types
A & B means "both A and B": an object with all properties of each.
type Timestamps = { createdAt: Date; updatedAt: Date };
type Customer = { id: number; name: string };
type CustomerRecord = Customer & Timestamps;
Use intersections to combine object types. (Intersecting unrelated primitives, such as string & number, gives never.)
Discriminated unions
The most useful pattern in TypeScript. Give each member a common field (the discriminant) with a unique literal type:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number }
| { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2; // shape is the circle here
case "rectangle": return shape.width * shape.height;
case "square": return shape.side ** 2;
}
}
Checking shape.kind narrows to exactly one member, so only its properties are accessible. This is TypeScript's version of Java's sealed interface with a pattern-matching switch.
Exhaustive checks with never
Make the compiler tell you when you add a new case and forget to handle it:
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "rectangle": return shape.width * shape.height;
case "square": return shape.side ** 2;
default: {
const unreachable: never = shape; // error here if a case is missing
throw new Error(`Unhandled shape: ${JSON.stringify(unreachable)}`);
}
}
}
If someone adds { kind: "triangle" ... } to Shape, the assignment to never fails to compile in this function, pointing straight to the code that needs updating.
Model states so impossible combinations cannot exist
A common beginner type for a data-loading screen:
type State = { loading: boolean; data?: Order[]; error?: string }; // allows loading: true AND error AND data
Many nonsensical combinations are allowed (loading with an error, no data and no error and not loading). A discriminated union allows only the valid ones:
type State =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: Order[] }
| { status: "error"; message: string };
function view(state: State): string {
switch (state.status) {
case "idle": return "";
case "loading": return "Loading...";
case "success": return `${state.data.length} orders`; // data exists only here
case "error": return state.message; // message exists only here
}
}
The same shape works for API results ({ ok: true; value: T } | { ok: false; error: E }), form steps and payment states. Making illegal states unrepresentable removes whole classes of bugs.
Tips and traps
- Optional fields versus unions:
{ email?: string }allowsundefined; ifnullis also meaningful, sayemail: string | null. filter(Boolean)does not narrow in older TypeScript (it does in recent versions for simple cases); use a type predicate:.filter((x): x is Order => x != null).- Widening:
let status = "paid"isstring, not"paid"; useconstoras const, or annotatelet status: Status. - Narrowing is lost in callbacks if the variable may be reassigned: copy into a
constfirst. innarrowing works on unions;objectand{}are broad types, preferRecord<string, unknown>orunknown.- Narrow once, early (guard clauses) to keep the rest of the function simple.
Common mistakes
- Using
asto force a type instead of narrowing. - Optional-property soup instead of a discriminated union.
- Type guards that do not match their check, which breaks type safety silently.
- Truthiness narrowing that removes
0or""when those are valid values. - Forgetting the default branch with
neverin aswitchover a union. - Trusting API data typed with a bare interface without run-time validation.
Try it yourself
- Write
format(value: string | number | null)returning a display string, narrowing each case. - Model a
Paymentas a discriminated union ofcard,upiandcashwith different fields, and write a function that describes it with an exhaustiveswitch. - Add a new variant and see the compile error from the
nevercheck. - Replace
{ loading: boolean; data?: ...; error?: ... }with the four-state union in a small component or function. - Add a Zod schema for an API response and infer its type.
Check yourself
What is narrowing?
TypeScript refining a variable's type to a more specific one after a check such as typeof, instanceof, in or equality, within the code where the check holds.
What is a discriminated union?
A union of object types that share a field with a unique literal value (the discriminant), so checking that field narrows to exactly one member.
How does never help in a switch over a union?
Assigning the unhandled value to a variable of type never in the default branch fails to compile if a union member is not handled, so adding a variant forces you to update the code.
What does a type predicate value is Order do?
It tells TypeScript that when the function returns true, the argument has type Order; the programmer is responsible for the check being correct.
Interview questions
How do you safely work with a value of type string | number?
Narrow it first, for example with typeof value === "string", then use the string or number methods in the matching branch.
How would you model API loading states in TypeScript?
With a discriminated union such as idle | loading | success(data) | error(message) so that data exists only on success and invalid combinations are impossible.
What is the difference between a union and an intersection type?
A union (A | B) is a value that is either A or B; an intersection (A & B) is a value that satisfies both A and B at once, combining their properties.
Summary
- Unions describe "one of"; narrowing with
typeof,in,instanceof, equality and type guards makes them usable. - Discriminated unions with a literal field plus an exhaustive
switchandnevergive safe, evolvable code. - Model states as unions so illegal combinations cannot be represented.
- Validate untrusted data at run time (Zod) and infer the type from the schema.
Going deeper
- TypeScript Handbook: Narrowing: all the narrowing forms, type predicates and exhaustiveness.
- TypeScript Handbook: Everyday types (unions): union basics.
- TypeScript Handbook: Object types (intersection): combining types.
- TypeScript Handbook: Type manipulation:
typeof,keyofand indexed access types.
See how much of this you can explain
A free mock interview asks you new questions on TypeScript for JavaScript developers for Frontend Developer and scores every answer, with what to fix.