Sub topic 11
Type predicates for narrowing
This chapter assumes you know TypeScript's typeof, in and equality narrowing, union types, and how to write a function with typed parameters and a return type. It builds on the earlier chapters on annotations and function types.
The problem: narrowing stops at the function boundary
Inline checks such as typeof x === "string" narrow a value right where you write them. If you move the check into a helper that returns boolean, the compiler only sees a boolean and forgets what the check proved.
function isStringPlain(value: unknown): boolean {
return typeof value === "string";
}
function shoutPlain(input: unknown): string {
if (isStringPlain(input)) {
// input is still `unknown` here
// return input.toUpperCase(); // error: 'input' is of type 'unknown'
}
return "";
}A type predicate fixes this. It is a special return type that says: "if I return true, the argument has this type."
Syntax of a type predicate
A type predicate is written as parameterName is Type in the return position.
function isString(value: unknown): value is string {
return typeof value === "string";
}
function shout(input: string | number): string {
return isString(input) ? input.toUpperCase() : String(input);
}The rules are:
- The name before
ismust be one of the function's parameters. - The type after
ismust be assignable to that parameter's type.function f(x: string): x is numberis an error, becausenumberis not a kind ofstring. - At runtime the function returns a plain
boolean. The predicate is erased during compilation.
What the compiler does with it
At each call in a condition, the compiler narrows the argument in both branches:
- In the true branch, the argument becomes the predicate type.
- In the false branch, the predicate type is removed from the argument's declared type.
The false branch is where predicates are most dangerous, as the gotchas section below shows.
Predicates on object types
Predicates are often used to tell apart members of a union that has no shared tag property.
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return "swim" in pet;
}
function move(pet: Fish | Bird): void {
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
}Here isFish hides the in check behind a name. Callers get narrowing without repeating the check, and you can change the check later in one place.
Predicates with array methods
The most common use is Array.prototype.filter. Its overload accepts a predicate function and returns an array of the narrowed type.
const mixed: (string | number | null)[] = ["a", 1, null, "b"];
const strings = mixed.filter(isString); // string[]
const withNulls = mixed.filter(x => x !== null); // (string | number)[] in TypeScript 5.5+Before TypeScript 5.5, the second call returned (string | number | null)[], because an arrow function returning boolean was not treated as a predicate. From 5.5 the compiler infers a predicate for simple functions like this one. The inference only applies when the function returns a boolean expression, does not mutate its parameter, and the result is true exactly when the parameter has the narrower type. For anything more subtle, write the predicate yourself.
A reusable generic predicate removes null and undefined:
function isDefined<T>(value: T | null | undefined): value is T {
return value != null;
}
const maybeNames: (string | undefined)[] = ["Ada", undefined, "Linus"];
const names = maybeNames.filter(isDefined); // string[]Predicates as function types
You can name the shape of a predicate with a type alias and pass predicates as arguments. This works well for building checks out of smaller checks.
type Guard<T> = (value: unknown) => value is T;
const isNumber: Guard<number> = (value): value is number =>
typeof value === "number";
function isArrayOf<T>(value: unknown, guard: Guard<T>): value is T[] {
return Array.isArray(value) && value.every(item => guard(item));
}
const data: unknown = JSON.parse("[1, 2, 3]");
if (isArrayOf(data, isNumber)) {
const total = data.reduce((sum, n) => sum + n, 0); // data: number[]
console.log(total);
}JSON.parse returns any, so assigning it to unknown first forces a check before use. This is the main reason to write predicates: they turn untrusted data into a typed value at one checkpoint.
Gotchas
The compiler does not verify your predicate
The compiler trusts the predicate completely. It does not check that the function body matches the claim. A wrong predicate is a lie the type system will believe.
function isPositive(value: unknown): value is number {
return typeof value === "number" && value > 0;
}
function describeValue(input: string | number): string {
if (isPositive(input)) {
return `positive ${input.toFixed(1)}`;
}
// The compiler thinks input is `string` here.
return input.toUpperCase(); // compiles, but throws a TypeError for -5
}The predicate says "returning false is not a number" in the false branch. But -5 is a number, so isPositive(-5) returns false, and the code calls toUpperCase on a number.
The rule: a predicate must be an "if and only if". It returns true exactly when the value has the type. If you need to test a property beyond the type, such as sign or length, return plain boolean and keep that check outside the predicate:
function describeFixed(input: string | number): string {
if (typeof input === "number") {
return input > 0 ? `positive ${input.toFixed(1)}` : `non-positive ${input}`;
}
return input.toUpperCase();
}Predicates tell you nothing about the object's other properties
A predicate like value is User that only checks typeof value === "object" will let a malformed object through. For data from outside your program, check every property you rely on.
type User = { id: number; name: string };
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"
);
}The "id" in value checks narrow value to include that property, which lets value.id type-check. This relies on TypeScript 4.9 or later.
Predicate parameters are tied to one argument
A predicate applies to a single parameter. A function with two parameters can only narrow one of them, so write two predicates if you need two narrowings.
Predicates survive only through direct calls
Narrowing works when the compiler can see the predicate's type at the call. If you store the function in a variable typed as (value: unknown) => boolean, the predicate part is lost.
const weaker: (value: unknown) => boolean = isString; // allowed, but loses the predicateA predicate function is assignable to a plain boolean-returning function type, but not the other way round.
Assertion functions: a related feature
An assertion function narrows by throwing instead of returning. Its return type is asserts value is Type. Code after the call is narrowed, because execution only continues if the check passed.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new TypeError("Expected a string");
}
}
function lengthOf(input: unknown): number {
assertIsString(input);
return input.length; // input: string
}Use a predicate when both outcomes are valid and the caller branches. Use an assertion function when a wrong type is an error and the caller should stop.
Choosing between inline checks and predicates
| Situation | Choice |
|---|---|
| One-off check used once | Inline `typeof` or `in` |
| Same check repeated in several places | Type predicate |
| Passing to `filter`, `find` or `some` | Type predicate (or rely on 5.5 inference) |
| Validating data from outside the program | Predicate, with every needed property checked |
| Failure must stop execution | Assertion function |
| Extra condition beyond the type, such as `> 0` | Plain `boolean`, not a predicate |
Summary
- A return type of
param is Typemakes a boolean function narrow its argument at the call site. - The true branch gets the type, and the false branch gets the declared type with that type removed.
- The compiler trusts the predicate, so it must be true exactly when the value has the type.
- Predicates work well with
filter, with generics, and as reusableGuard<T>aliases. - Use
asserts value is Typewhen a failed check should throw.
Exercise
This function compiles. What goes wrong when it is called with the empty string, and how would you fix it? function isNonEmpty(value: string | number): value is string { return typeof value === "string" && value.length > 0; } function size(input: string | number): number { if (isNonEmpty(input)) { return input.length; } return input.toFixed(0).length; }
Show answer
For "", isNonEmpty returns false, so the compiler narrows input to number in the false branch. But "" is a string, so input.toFixed(0) throws a TypeError at runtime. The predicate claims more than a type check can prove, because it also tests length. Fix it by making the predicate test only the type (return typeof value === "string") and checking input.length > 0 separately, or by changing the return type to boolean and using an inline typeof check in size.