Lesson 37 of 50TypeScript
Unions and Narrowing
Model "this or that" with unions, narrow them safely, and make impossible states impossible with discriminated unions.
Real values are rarely one thing. An id is a string or a number. A request is loading, done, or failed. A config value is set or missing. Unions describe those choices, and narrowing is how TypeScript follows your if statements to know which case you are in. This is the feature that makes TypeScript feel smart, and discriminated unions show up in every React codebase and every senior-level interview.
Union types
A union A | B means "a value of type A or type B". You can only use what is available on every member, until you check which one you have.
function formatId(id: string | number) {
return id.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
}The fix is to check the type. Inside the check, TypeScript narrows id to the matching member.
Press Run (⌘ Enter) to see what happens.Narrowing step by step
TypeScript reads your control flow (if, return, switch, throw) and keeps track of what a variable can still be at each line. This is called control flow analysis.
At the top of the function, input could be any of the three.
The narrowing tools you will use:
| Check | Narrows | Example |
|---|---|---|
typeof | Primitives | typeof x === "string" |
| Equality | Literals, null, undefined | x === null, status === "done" |
| Truthiness | Removes null, undefined, "", 0 | if (user) |
in | Objects by property | "email" in contact |
instanceof | Class instances | err instanceof TypeError |
Press Run (⌘ Enter) to see what happens.function show(count: number | undefined) {
if (count) {
return "Count: " + count;
}
return "No count";
}Discriminated unions
The most useful pattern in TypeScript. Give every member of a union a shared literal property, usually kind, type or status. Checking that one property narrows the whole object. This is a discriminated union (also called a tagged union).
type RequestState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: string[] }
| { status: "error"; message: string };Compare that with the shape many beginners write:
type RequestState = {
isLoading: boolean;
data?: string[];
error?: string;
};
// Allows nonsense: isLoading true AND data AND error all at once.The discriminated version makes impossible states impossible. You cannot have data while loading, and you cannot read message without first proving the status is "error".
Press Run (⌘ Enter) to see what happens.What does this print?
type Result =
| { ok: true; value: number }
| { ok: false; error: string };
function show(r: Result) {
return r.ok ? r.value * 2 : r.error.length;
}
console.log(show({ ok: true, value: 21 }), show({ ok: false, error: "nope" }));Exhaustiveness checking with never
What happens when someone adds a new state, say { status: "cancelled" }, and forgets to update render? You want a compile error, not a silent undefined. Assign the leftover value to never in the default branch.
function render(state: RequestState): string {
switch (state.status) {
case "idle": return "Press search";
case "loading": return "Loading...";
case "success": return `Found ${state.data.length}`;
case "error": return "Error: " + state.message;
default: {
const unhandled: never = state;
// Error (after adding "cancelled"):
// Type '{ status: "cancelled"; }' is not assignable to type 'never'.
throw new Error("Unhandled state");
}
}
}When every case is handled, nothing is left and state has type never in default, so the assignment compiles. The moment a case is missing, the leftover member cannot be assigned to never, and the compiler points straight at the switch you forgot.
const unhandled: never = state compile when every case is handled?Type predicates and assertion functions
Sometimes the check is too complex for an inline if. Move it into a function and give it a type predicate return type, value is Type. When it returns true, callers get the narrowing.
Press Run (⌘ Enter) to see what happens.Since TypeScript 5.5, simple callbacks like x => x != null infer the predicate automatically, so filter returns number[] without the annotation.
An assertion function is the throwing version. Its return type is asserts value is Type: if it returns at all, the value is narrowed for the rest of the scope.
function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error(`${name} is required`);
}
}
const apiKey = process.env.API_KEY; // string | undefined
assertIsDefined(apiKey, "API_KEY");
apiKey.length; // string from here onin narrowing in depth, and satisfies with unions
The table above lists in as "objects by property". Two details decide whether it narrows the way you expect.
Optional properties keep both members. "permissions" in u narrows to the members where permissions is required or optional, because an optional property may be present. If one member declares permissions?: undefined as a way to say "never has it", the check does not remove that member:
type Admin = { name: string; permissions: string[] };
type Guest = { name: string; permissions?: undefined; expires: Date };
function show(u: Admin | Guest) {
if ("permissions" in u) {
u; // still Admin | Guest: a Guest may carry permissions: undefined
}
}The fix is to discriminate on something both members declare as a required literal (role: "admin" | "guest"), which is one more reason a shared tag beats property sniffing.
Unknown properties get added. Since TypeScript 4.9, in also works on objects whose type does not mention the key. After "id" in x, TypeScript treats x as object & Record<"id", unknown>, so you can read x.id and narrow it further. That makes hand-written guards on unknown data much shorter:
function readId(x: unknown): string | null {
if (typeof x === "object" && x !== null && "id" in x && typeof x.id === "string") {
return x.id; // string
}
return null;
}satisfies keeps the narrow member. The satisfies operator (TypeScript 4.9+) checks that a value matches a type without changing the type TypeScript infers for it. With unions that difference matters a lot. Annotate a lookup table with a union type and every entry becomes the whole union, so you must narrow again on every read:
type Route = { kind: "page"; path: string } | { kind: "redirect"; to: string };
const annotated: Record<string, Route> = {
home: { kind: "page", path: "/" },
old: { kind: "redirect", to: "/" },
};
annotated.home.path; // Error: 'path' does not exist on type 'Route'
annotated.tyop; // No error: any string key is allowed
const routes = {
home: { kind: "page", path: "/" },
old: { kind: "redirect", to: "/" },
} satisfies Record<string, Route>;
routes.home.path; // OK: TypeScript knows home is the "page" member
routes.tyop; // Error: there is no tyop keyWith satisfies, each entry is still checked against Route (a typo in kind or a missing path is an error), but the variable keeps its exact shape. Use annotation when you want callers to treat every entry the same; use satisfies for config objects where you know which entry is which.
Narrowing that does not survive callbacks
Narrowing is a property of a place in your code, not of the value. When you create a function, TypeScript has to decide whether the narrowing at that line still holds whenever the function eventually runs. Sometimes it cannot promise that, and the narrowing is dropped.
type State = { user: { name: string } | null };
function greetLater(state: State) {
if (state.user) {
state.user.name; // fine here
setTimeout(() => {
console.log(state.user.name);
// Error: 'state.user' is possibly 'null'.
}, 1000);
}
}TypeScript is right to worry. By the time the timer fires, some other code may have set state.user = null. The check happened a second ago, on a different turn of the event loop. The same applies to forEach, map, event handlers and promise callbacks: TypeScript does not know when, or how often, a callback runs.
The rules in current TypeScript:
- A
constvariable or a parameter that is never reassigned keeps its narrowing inside callbacks. Nothing can change what it points to. - A
letvariable keeps its narrowing in a callback only if the callback is created after the last assignment to it (TypeScript 5.4+). If there is any assignment later in the function, the narrowing is dropped. - A property path like
state.userloses narrowing inside callbacks, because any code anywhere could write to that property.
The fix is almost always the same: copy the narrowed value into a const.
function greetLater(state: State) {
const user = state.user;
if (user) {
setTimeout(() => console.log(user.name), 1000); // OK: user is a const
}
}That is not just a trick to silence the compiler. It changes the behaviour to "greet the user who was logged in when I checked", which is usually what you meant.
There is an opposite hole. TypeScript does not forget property narrowing after an ordinary function call, even though that function could have changed the property:
if (state.user !== null) {
logout(state); // sets state.user = null inside
state.user.name; // no error, but crashes at runtime
}Resetting every narrowing after every call would make the language unbearable to use, so the team chose this trade-off on purpose. It is one of the few places where TypeScript is knowingly unsound. Mutation is where types and reality drift apart, which is another reason to prefer immutable updates.
strict?function run(input: string | null, box: { value: string | null }) {
if (input !== null && box.value !== null) {
[1, 2].forEach(() => input.length); // line A
[1, 2].forEach(() => box.value.length); // line B
const v = box.value;
[1, 2].forEach(() => v.length); // line C
}
}Modelling async state as a discriminated union
The RequestState union above is the starting point. Real screens add two requirements, and the union handles both without extra booleans.
Keep showing old data while refetching. Users hate a list that flashes to a spinner on every refresh. Let the loading and error members optionally carry the previous data. Ignore late replies. If a request resolves after the user has already moved on, the reply should not overwrite the screen. Both rules fit naturally into a reducer, a pure function that takes the current state and an action and returns the next state:
Press Run (⌘ Enter) to see what happens.The last line is the interesting one. A reply arrives while the state is error, not loading, so the reducer drops it. The union turned "which transitions are legal" into a few if statements that the compiler checks.
Nothing requested yet. The only legal action is fetch.
You do not always write this by hand. TanStack Query, for example, exposes a status field ("pending" | "error" | "success") and a separate fetchStatus ("fetching" | "paused" | "idle"), because "do I have data?" and "is a request in flight?" are two different questions. Its result type is a discriminated union too, so checking status === "success" narrows data to defined. Once you can model the union yourself, those library types read like plain English.
switch (true) narrowing
Sometimes the cases are not values of one field but a list of conditions. Before TypeScript 5.3 you wrote an if/else if ladder. Now switch (true) narrows too: each case expression is treated like an if condition, and the cases that came before it count as failed.
Press Run (⌘ Enter) to see what happens.In default, TypeScript has removed null, string and number, so value is Date and toISOString is allowed. Two cautions. Write the cases as positive checks: a negated case such as case typeof x !== "number": does not narrow the cases after it, so you will get "possibly unknown" errors where you did not expect them. And some teams find switch (true) harder to read than if chains; it shines when every branch returns, like the classifier above.
default branch of describe above, what is the type of value?Match the situation to the narrowing tool.
Area of a discriminated union
Shapes are a discriminated union: every member has a kind field that says which one it is.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };Write area(shape: Shape): number. Use a switch on shape.kind and add an exhaustiveness check with never in the default branch.
{ kind: "rect", width: 3, height: 4 } → 12
{ kind: "circle", radius: 1 } → 3.14159...Write a type guard
Data from JSON.parse or fetch has no trustworthy type. Write a type predicate that checks it at runtime:
type User = { id: number; email: string; name?: string };
function isUser(value: unknown): value is UserReturn true only when:
valueis a non-null object (and not an array),idis a number andemailis a string,nameis either missing or a string.
Extra properties are allowed.
- union type
A | B: a value that is one of several types. You can only use what all members share until you narrow.- narrowing
- TypeScript refining a union to a smaller type based on checks like
typeof,in,instanceofand equality. - discriminated union
- A union of object types that share a literal property (like
kind) used to tell them apart. - exhaustiveness check
- Assigning the leftover value to
neverso the compiler errors when a union member is not handled. - type predicate
- A return type
value is Ton a boolean function, so callers get narrowing when it returns true. - assertion function
- A function with return type
asserts value is Tthat throws if the check fails and narrows otherwise. - control flow analysis
- How TypeScript follows
if,return,switchand assignments to work out a variable's type at each line. - reducer
- A pure function
(state, action) => nextState, a natural home for the legal transitions of a discriminated union.