Basic narrowing: typeof, instanceof, in, truthiness
Narrowing is control flow analysis: after a type check the compiler knows a more precise type of the variable in that branch. It works for typeof, instanceof, in, comparisons and an early return. The compiler handles the type, not the meaning of the condition: if (amount) also discards zero, so for numbers use an explicit comparison. Other traps: typeof null gives object, and instanceof does not work for data parsed from JSON.
TypeScript · Narrowing
A transfer of 0 shows as "n/a" while the test for a non-zero amount is green. What did if (amount) swallow?
A formatting function takes an optional amount and checks it with if (amount). A test with 150 passes and nobody thinks about zero. Yet zero is a valid value in a financial domain, and that check discards it. This is a typical narrowing situation: the compiler helped with the type, but a human wrote the condition. The lesson covers how TypeScript narrows a type after a check, which tools exist and where they are tricky.
How it works and why. Narrowing is control flow analysis. The compiler reads if, switch, an early return and throw, and at each point of the code knows which variants of the type are still possible. For a variable of type string | number, after typeof v === 'number' the type is number in the if branch and string in the rest. It is designed so because JavaScript already uses exactly such checks: TypeScript adds no new syntax, it understands the existing one. Hence the rule: only what is visible in the code narrows. A condition computed elsewhere and stored in a variable gives no narrowing (the compiler handles simple cases, but do not rely on it for complex ones).
What narrows
Figure 1. The four main checks. An exact comparison is the most reliable, the others have exceptions.
typeValue = string | number | null | Date | { code: string };
functionshow(v: Value): string {
if (v === null) return'null';
if (typeof v === 'string') return v.trim();
if (typeof v === 'number') return v.toFixed(2);
if (v instanceofDate) return v.toISOString();
return v.code; // only { code: string } is left
}
typeof returns one of the strings 'string', 'number', 'boolean', 'undefined', 'object', 'function', 'bigint', 'symbol'. A trap: typeof null === 'object', so objects get a separate !== null. instanceof works with classes and checks the prototype chain, so it fails for an object created in another realm (an iframe) and for plain JSON data. in checks that a property exists and narrows a union of objects. Equality narrows a union of literals. Under strict the catch variable is unknown (the useUnknownInCatchVariables option), so the pattern below is routine:
Example: truthiness and zero. Back to the function from the start.
functionformatAmount(amount?: number): string {
if (amount) return amount.toFixed(2);
return'n/a';
}
formatAmount(0); // 'n/a', but it should be '0.00'
The if (amount) check discards not only undefined but all "falsy" values: 0, -0, 0n, an empty string, NaN, false and null. For an optional amount that is an error the compiler cannot see: the type is narrowed correctly, but the condition is wrong. A test with a non-zero amount does not show it. What is needed is a check of exactly what you mean:
Zero, an empty string and NaN fall into "no value". For amounts, counters and quantities that is data loss.
Right
amount !== undefined
Discards only what you meant. Zero remains a valid amount.
Figure 2. Truthiness fits only where zero and an empty string really mean "no value".
Limits and alternatives. Narrowing lives within the control flow. A narrowed let or parameter may become wide again inside a callback if it is assigned after the callback is created or inside another function; a const stays narrow. After a plain function call the narrowing is kept: the compiler optimistically assumes the call did not touch the variable. Newer compiler versions keep narrowing in closures better when the variable is not reassigned after the check (this appeared in TypeScript 5.4), but it is more reliable to pull the value into a const. An early exit narrows as well: after if (!account) throw new Error('not found') the variable is no longer undefined. When many checks are needed they move into a custom type guard or a schema.
Common mistakes.
if (value) for numbers and strings where 0 or an empty string are valid: data is silently lost.
typeof x === 'object' without !== null: the next field access fails on null.
instanceof for JSON data: these are plain objects, not class instances, so the check is always false.
Relying on the narrowing of a let inside a callback: the value could have changed and the type is wide again.
Check yourself
Why does if (amount) narrow number | undefined to number correctly by type, yet is still a bug for an amount formatter?
Answer
The type is narrowed correctly, but the condition also discards 0. Narrowing is about the type, not the meaning of the check, so for zero you need the comparison amount !== undefined.
In catch (err) the code err.message does not compile under strict. Why, and which check fixes it?
Answer
Anything can be thrown, so err in catch is unknown. The check err instanceof Error narrows it to Error, and then message is available.
Related lessons: “Discriminated unions”, “User-defined type guards and assertion functions”, “Comparison: == and ===, ||, ?? and ?.”.
In an interview.Junior: Narrowing is when, after a typeof, instanceof, in or comparison check, TypeScript understands a more precise type of the variable. Middle/Senior: The compiler analyses control flow, and the logic of the check stays with me: typeof null gives object, truthiness discards zero, instanceof fails for JSON and the narrowing of a let is lost in callbacks. So for numbers I use an explicit comparison and for outside data a schema check.
Discriminated unions
A discriminated union is a union of object types with a shared literal property, and checking it narrows the whole variable to one variant. Invalid field combinations do not compile, and an assertNever that takes never in the default branch makes a new variant highlight every place to update. The discriminant must be a literal, not a wide string. At runtime nothing is guaranteed, so network data is checked with a schema.
TypeScript · Narrowing
A new "crypto" payment method appeared and the report helper stays silent. How do you make the compiler show every place?
A payment can be a card, an IBAN transfer or a wallet, and each method has its own fields. If you describe that with one type full of optional fields, helpers start demanding ! and a new method quietly drops out of every if. A discriminated union solves both problems: the type describes exactly the allowed combinations of fields, and the compiler watches that every variant is handled.
How it works and why. A discriminated union is a union of object types with a shared literal property (the discriminant): kind, status, ok. Checking that property (===, switch) narrows the whole variable to one variant, and the fields of that variant become available without !. It works because every variant has a unique literal value: the compiler sees which variants remain for each value. The discriminant can be a string, a number, a boolean, null or undefined, but not the wide type string: with that the variants cannot be told apart.
Example: from optional fields to a union. First, one type with optional fields:
One type or a union
Wrong
A pile of optional fields
You can build a payment with no field at all or with all of them. Every helper uses ! and nobody notices a new method.
Right
A union with a discriminant
Impossible states cannot be represented. Fields are available without ! after checking kind.
Figure 1. A union leaves impossible field combinations out of the type; one type with optional fields allows them.
The union lists the allowed combinations: every variant has its own kind and fields.
switch on the discriminant narrows p in every branch.
In default the variable has type never: if a variant is forgotten, the call will not compile.
The never trick is called an exhaustiveness check. Extend the type and the compiler points at each place that needs an update:
A new variant and exhaustiveness
Figure 2. Until the branch is added assertNever does not compile: a variant cannot be forgotten.
typePayment =
| { kind: 'card'; pan: string }
| { kind: 'iban'; iban: string }
| { kind: 'wallet'; walletId: string }
| { kind: 'crypto'; address: string };
// in describe: assertNever(p)// Argument of type '{ kind: "crypto"; address: string; }'// is not assignable to parameter of type 'never'
The same applies to API responses. A boolean ok field is a discriminant too:
typeApiResult<T> =
| { ok: true; data: T }
| { ok: false; error: { code: string; message: string } };
function unwrap<T>(res: ApiResult<T>): T {
if (!res.ok) {
thrownewError(res.error.code + ': ' + res.error.message);
}
return res.data; // here res is the ok: true branch
}
Limits and alternatives. Without default and with an annotated return type, strict also shows that the function may return undefined if switch does not cover every variant, but assertNever gives a clear message and works at runtime if the data turns out different. That is another limit: the union exists only in the compiler. A value from the network with an unknown kind will reach default, so outside data is checked by a schema. zod has z.discriminatedUnion for that, and the type is derived from it:
A discriminant of type string: variants are indistinguishable and narrowing does not work. Literals are needed.
switch without a default using never: a new variant is silently skipped.
A type with optional fields instead of a union and ! in helpers: the compiler does not help.
Checking the variant through if (p.pan) instead of the discriminant: it does not work for a union where the field is not in all variants.
Check yourself
A variant { kind: 'crypto' } was added to the union and describe with default: return assertNever(p) stopped compiling. A bug or a benefit?
Answer
A benefit. In defaultp is now { kind: 'crypto' } and not never, so the compiler demands a branch. That is how all places needing an update are found.
Why is type Status = { status: string; error?: string } worse than the union { status: 'ok' } | { status: 'error'; error: string } for an API response?
Answer
The first allows "error" without a message and "ok" with one, and after checking the status the field stays optional. In the union the message is required where it exists and absent where it does not.
Related lessons: “Basic narrowing: typeof, instanceof, in, truthiness”, “User-defined type guards and assertion functions”, “any, unknown and never”.
In an interview.Junior: It is a union with a shared literal field such as status or kind; checking the field narrows the whole object. Middle/Senior: Invalid combinations of fields simply do not compile, and assertNever in default turns exhaustiveness into a compiler check: a new variant instantly lights up every place. Data from the network I check with a schema, since a union guarantees nothing at runtime.
User-defined type guards and assertion functions
A type guard is a function returning value is T; when it returns true, the compiler narrows the variable to T. An assertion function with asserts value is T throws on failure and narrows the type afterwards. The compiler does not verify that the body really proves T, so an incomplete guard gives a wrong type silently. For API responses prefer a schema that infers the type.
TypeScript · Narrowing
A guard says true for an object with a string balance and the compiler believes it. Who checks the checker?
An API response arrives as unknown and the compiler has to be convinced it is an Account. Built-in checks are not enough, so the automation engineer writes a custom guard function. It is handy, but has a weak spot: the compiler does not verify its body. A wrong function gives a wrong type, and the error shows up far from the cause. The lesson covers guard functions, assertion functions and when to replace them with a schema.
How it works and why. A type guard is a function with the return type value is T (a type predicate). For the compiler it is a contract: if the function returned true, the variable has type T in the if branch; if false, T is excluded from the type in the else branch. The compiler does not look into the function body, since types have no access to execution logic. It trusts the signature, just as it trusts as. The difference is that a guard is written and tested once, while as is scattered through the code. An assertion function with asserts value is T returns nothing and throws instead, and after its call the type is narrowed for the rest of the scope.
interfaceAccount { id: string; balance: number; currency: string }
1functionisAccount(v: unknown): v is Account {
if (typeof v !== 'object' || v === null) returnfalse;
2const o = v asRecord<string, unknown>;
return (
3typeof o.id === 'string' &&
typeof o.balance === 'number' &&
typeof o.currency === 'string'
);
}
The predicate v is Account: the compiler will believe it without checking the body.
The only as merely lets the code read properties of an already checked object as unknown: it does not promise the result type.
Every field is checked separately. A forgotten field means a wrong type further in the code.
Example: a guard that lies. A simplified guard that checks only that a field exists lets wrong data through:
functionisAccount(v: unknown): v is Account {
returntypeof v === 'object' && v !== null && 'id'in v;
}
const body: unknown = await res.json(); // { id: "1", balance: "100" }if (isAccount(body)) {
body.balance.toFixed(2); // compiles, TypeError at runtime
}
A guard or a schema
Wrong
An incomplete guard
Lets balance as a string through. The type says number, the runtime throws TypeError far from the check.
Right
A full guard or a schema
All fields are checked, and in a schema the type and the check come from one description and cannot drift apart.
Figure 1. The compiler believes the guard, so the quality of the check rests on the author.
There are two fixes. A full guard, as above, suits small types. For API response models a schema is better: it checks data at runtime, says exactly what is wrong, and defines the type from one description.
Assertion functions are handy in tests for values that must exist, where absence is a test failure. They throw with a clear message and remove the need for ? and !:
function assertDefined<T>(v: T, msg: string): asserts v is NonNullable<T> {
if (v === undefined || v === null) thrownewError(msg);
}
functionassert(cond: unknown, msg: string): asserts cond {
if (!cond) thrownewError(msg);
}
const row = rows.find((r) => r.txId === id);
assertDefined(row, 'transaction ' + id + ' not found');
row.amount; // no ? and no !
There is a technical restriction: for a call to an assertion function to narrow the type, it must be declared with an explicit annotation. This works for a function and for a variable with an explicitly stated type, but an arrow function without an annotation causes a compiler error. Separately about arrays: a guard predicate in filter removes undefined from the result type.
const found: (Row | undefined)[] = ids.map((id) => byId.get(id));
// an explicit predicateconst rows1 = found.filter((r): r is Row => r !== undefined);
// since TypeScript 5.5 the predicate is inferred in simple casesconst rows2 = found.filter((r) => r !== undefined);
Limits and alternatives. A guard fits narrow, well-known shapes: checking an error with a code, checking a DOM element. When the shape is large or changes together with the API, a hand-written function becomes a burden: it has to be updated next to the type, and a mismatch lights up nowhere. A schema (zod, valibot, ajv) solves that and adds an error message. One more trap: a guard that wrongly returns false can narrow the else branch incorrectly, so any mistake in a predicate does harm in both directions.
Common mistakes.
A guard that checks only some fields: the type promises more than is guaranteed.
A guard function nobody tested: its bug hides behind a green compile.
Writing as Account instead of a guard: there is no check at all.
An assertion function as an arrow whose variable has no type annotation: the call does not compile (TS2775).
Check yourself
The guard isAccount checks only typeof o.id === 'string' and returns v is Account. What happens with the object { id: '1' } and where does the problem show up?
Answer
The guard returns true and the compiler treats the object as Account. There is no balance, so body.balance.toFixed(2) compiles and fails at runtime: the error is far from the check.
How does an assertion function asserts v is T differ from a guard v is T in use?
Answer
A guard returns a boolean and is put in an if; an assertion function returns nothing and throws, and the type is narrowed after the call without an if. For values that must exist in a test it is a short way to narrowing with a good message.
Related lessons: “Basic narrowing: typeof, instanceof, in, truthiness”, “Discriminated unions”, “Why generics: a typed API client”.
In an interview.Junior: A type guard is a function with value is T: after it TypeScript narrows the type. An assertion function with asserts throws and narrows the type further down the code. Middle/Senior: The compiler does not check a guard body, so an incomplete check gives a wrong type with no warning. For API responses I use a schema from which the type is derived, and keep guards and assertions for narrow checks in tests.