Type guards and assertion functions
Moving narrowing checks into reusable functions with `x is T` predicates and `asserts` signatures, and what TypeScript 5.5 now infers for you.
typeof, instanceof, and in narrowingDiscriminated unionsany, unknown, never, and void
Type guards and assertion functions
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Narrowing only follows checks written inline; move the same check into a function that returns `boolean` and the caller learns nothing from calling it.
- A return type of `value is T` turns a function into a type guard: when it returns `true`, the argument narrows to `T`, and when it returns `false`, `T` is removed from it.
- The checker does not verify that a type predicate's body matches its claim, so a wrong guard compiles and spreads a false type everywhere it's called.
- Since TypeScript 5.5, a function with no return type annotation whose body is a single check like `x !== undefined` gets an inferred type predicate, which is why `array.filter((x) => x !== undefined)` now narrows the array.
- An assertion function, with return type `asserts value is T` or `asserts condition`, narrows by throwing: if the call returns at all, the condition held, so the narrowing applies to every line after the call.
- Assertion functions only narrow when every name in the call target has an explicit type annotation, so declare them with `function` or annotate the variable that holds them.
A check that stops working when you name it
You have data from somewhere untrusted and a narrowing check that proves it’s a User. It’s long, so you move it into a function:
type User = { id: number; name: string };
function isUser(value: unknown): boolean {
return (
typeof value === "object" && value !== null &&
"id" in value && typeof value.id === "number" &&
"name" in value && typeof value.name === "string"
);
}
function greet(data: unknown) {
if (isUser(data)) {
return data.name;
// error: 'data' is of type 'unknown'.
}
}
The same check, written inline, would have narrowed. Through a function, it doesn’t. Control flow analysis follows the code in front of it; it doesn’t read a function’s body to work out what a true result means. A boolean return type says “yes or no” and nothing about which question was answered.
Type predicates: value is T
The fix is to put the meaning in the return type:
function isUser(value: unknown): value is User {
return (
typeof value === "object" && value !== null &&
"id" in value && typeof value.id === "number" &&
"name" in value && typeof value.name === "string"
);
}
function greet(data: unknown) {
if (isUser(data)) {
return data.name.toUpperCase(); // data: User
}
}
value is User is a type predicate. The function still returns a plain boolean at runtime. What changes is what the caller learns: true narrows the argument to User, and false removes User from its type. The false direction matters too. If the argument were User | string, the else branch would see string.
The checker trusts you
A type predicate is a claim, and TypeScript doesn’t verify it. It only checks that the body returns a boolean:
function isString(value: unknown): value is string {
return typeof value === "number"; // compiles, and is wrong
}
Every call site will now treat numbers as strings. Think of a guard like a building’s ID check at the front desk: everyone inside trusts the badge, so a broken desk lets anyone through. Keep guards small, make them check every property the type promises, and test them.
Predicates TypeScript infers for you
The classic place a predicate was needed is filter. Before TypeScript 5.5, removing undefined from an array left the type unchanged, and people wrote (x): x is string => x !== undefined by hand. Since 5.5, the checker infers a predicate when a function has no return type annotation, a single return of a boolean check, and doesn’t change its parameter:
const ids = ["a", undefined, "b"];
const clean = ids.filter((id) => id !== undefined); // clean: string[]
There’s a condition worth knowing. A predicate is inferred only if false proves the value is not the narrowed type. Truthiness fails that test:
const counts = [0, 1, undefined];
const kept = counts.filter((n) => !!n); // kept: (number | undefined)[]
!!n is false for 0, so a false result doesn’t prove n isn’t a number, and no predicate is inferred. That’s correct, since 0 really was dropped. Videos and articles older than mid-2024 often show the hand-written version for cases that now infer on their own.
Assertion functions: narrowing by throwing
Sometimes you don’t want an if. You want to check, fail hard if the check fails, and carry on. An assertion function does that:
function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
if (value === undefined || value === null) {
throw new Error(`${name} is missing`);
}
}
function assert(condition: unknown, message: string): asserts condition {
if (!condition) throw new Error(message);
}
function start(port: string | undefined, mode: string | number) {
assertIsDefined(port, "PORT");
port.toUpperCase(); // port: string
assert(typeof mode === "string", "mode must be a string");
mode.toUpperCase(); // mode: string
}
asserts value is T narrows a parameter. asserts condition narrows by whatever the passed expression proves, as if it had been written in an if. Either way the function returns void when the check holds and throws when it doesn’t. If execution reaches the next line, the checker treats the check as passed for the rest of the scope.
The explicit-annotation rule
One rule trips people up. Every name in the call target of an assertion function must have an explicit type annotation. An arrow function stored in an unannotated const doesn’t qualify:
const assertIsString = (value: unknown): asserts value is string => {
if (typeof value !== "string") throw new Error("not a string");
};
function shout(raw: unknown) {
assertIsString(raw);
// error TS2775: Assertions require every name in the call target
// to be declared with an explicit type annotation.
}
The variable’s type is inferred, and the checker needs the type available before it runs control flow analysis on the code around the call. Use a function declaration, or annotate the variable: const assertIsString: (value: unknown) => asserts value is string = ....
About the video
Kyle Cook’s five-minute video covers type predicates: a helper check that fails to narrow, then x is T fixing it. It predates TypeScript 5.5, so some of its motivating cases now infer a predicate without help, as described above. It doesn’t cover assertion functions. Matt Pocock’s short clip linked below demonstrates asserts x is T in under two minutes.
Check yourself
Why doesn't `if (isUser(data)) { data.name }` compile when `isUser` is declared as `(value: unknown): boolean`?
TypeScript narrows on checks it can see inline, but it doesn't look inside a function body to work out what a `true` result proves. A `boolean` return says nothing about the argument, so `data` stays `unknown`. Changing the return type to `value is User` gives the caller that information.
What happens if a type predicate's body is wrong, for example `function isString(v: unknown): v is string { return typeof v === "number"; }`?
It compiles. TypeScript only checks that the body returns a `boolean`; it trusts the predicate's claim. Every caller then treats numbers as strings, and the error only surfaces at runtime. Type guards deserve the same care and tests as any other code.
Why does `[1, 0, undefined].filter((n) => !!n)` stay `(number | undefined)[]` even in TypeScript 5.5, while `.filter((n) => n !== undefined)` becomes `number[]`?
An inferred predicate needs the `false` result to prove the value is not the narrowed type. `!!n` returns `false` for `0`, which is a `number`, so a `false` result doesn't rule out `number` and no predicate is inferred. `n !== undefined` is false only for `undefined`, so `n is number` can be inferred.
How does an assertion function narrow when it doesn't return a boolean?
Its return type is `asserts value is T` or `asserts condition`, and it throws when the check fails. Code after the call only runs if it returned normally, so the checker treats the check as passed and narrows for the rest of the scope.
`const assertIsString = (v: unknown): asserts v is string => { ... }` gives error TS2775 at the call site. What causes it, and how do you fix it?
Assertions require every name in the call target to be declared with an explicit type annotation, and the variable `assertIsString` has an inferred type. Declare it with `function assertIsString(...)`, or annotate the variable, as in `const assertIsString: (v: unknown) => asserts v is string = ...`.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.