Skip to content
jshacks.dev
TypeScript

Inferred Type Predicates

TypeScript 5.5 infers type predicates for simple guard functions, so filter calls narrow without an annotation. See the rules, the limits and exact errors.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite, npm and Node.js logos.

For years, one of the most common small annoyances in TypeScript was filtering null out of an array. You wrote items.filter(x => x !== null), and the result was still typed as an array that might contain null, so you either wrote a type predicate by hand or cast the result. TypeScript 5.5 removed that friction by inferring type predicates from the body of a function. This post explains what an inferred type predicate is, the exact conditions under which the compiler infers one, the cases where it refuses and why, and when you should still write the predicate yourself. It describes TypeScript 6.x, which keeps the feature, and the native compiler preview that TypeScript 7 is built on behaves the same way. The feature was introduced in the TypeScript 5.5 release notes, and type predicates themselves are covered in the handbook chapter on narrowing.

Type predicates in one minute

A type predicate is a special return type that tells the compiler what a boolean result means. The signature (x: unknown) => x is string says that if the function returns true, the argument is a string. A caller can then use the function in an if, and the compiler narrows the variable inside the branch. Array methods such as filter have an overload that accepts a predicate and returns an array of the narrowed type.

Before 5.5, you wrote the predicate yourself.

manual.tsTypeScript
function isString(x: unknown): x is string {
  return typeof x === "string";
}

const mixed: unknown[] = ["a", 1, "b", null];
const strings = mixed.filter(isString);
const first: string = strings[0];
console.log(strings);
Text
[ 'a', 'b' ]

The array strings has type string[], because filter used the predicate overload, and the program prints the two strings at run time. The cost of this style was that every small guard needed a hand-written return type, and the arrow function in filter(x => x !== null) could not carry one without extra noise.

What 5.5 infers

When a function meets certain conditions, the compiler infers the predicate itself. The same guard written without the annotation now has the same effect.

inferred.tsTypeScript
const isString = (x: unknown) => typeof x === "string";

const mixed: unknown[] = ["a", 1, "b", null];
const strings = mixed.filter(isString);
const first: string = strings[0];

const values = [1, null, 2, undefined, 3];
const numbers = values.filter(v => v !== null && v !== undefined);
const total: number = numbers[0];
console.log(numbers);
Text
[ 1, 2, 3 ]

Hovering over isString in an editor shows the inferred signature (x: unknown) => x is string. The numbers array is number[], with no cast and no annotation, which is exactly the case people wanted. Before 5.5 the same code gave (number | null | undefined)[] and the assignment on line 9 would have failed.

The conditions for inference

The compiler infers a predicate x is T for a function only when all of these hold. The function has no explicit return type annotation, since an annotation always wins. It has a single return statement, or is an arrow function with an expression body, and does not return a type predicate already. It has exactly one parameter, which is used for the refinement, and it does not mutate that parameter. It returns a boolean expression that is tied to a refinement of that parameter, such as a typeof check, an instanceof check, a comparison with null, or a combination of these.

The last condition has a second half that matters more than the others: the function must return true if and only if the parameter has the narrower type. If the function returns true, the argument must be a T. And if it returns false, the argument must not be a T. The compiler checks both directions by narrowing the parameter on the true and false branches of the returned expression, and infers the predicate only when the two branches together partition the original type.

The case where inference refuses

The second direction is where the interesting failures come from. Consider the idiom of filtering out falsy values.

falsy.tsTypeScript
const values: (number | undefined)[] = [0, 1, undefined, 2];

const truthy = values.filter(v => !!v);
const nums: number[] = truthy;
console.log(truthy);
Text
falsy.ts(4,7): error TS2322: Type '(number | undefined)[]' is not assignable to type 'number[]'.
  Type 'number | undefined' is not assignable to type 'number'.
    Type 'undefined' is not assignable to type 'number'.

Running the filter would print [ 1, 2 ], since 0 and undefined are both falsy and both removed. The compiler does not infer v is number, and the reason is the 0. When the function returns false, the argument might be undefined, but it might also be the number 0. So false does not imply "not a number", the iff condition fails, and the compiler refuses to infer a predicate. A predicate here would be a lie, because it would claim that every value removed was not a number, and 0 was a number that was removed.

This refusal protects you. If the compiler inferred v is number for !!v, the false branch in a user's if would narrow v to undefined and exclude 0, which is wrong. The strict !== undefined check from the earlier example does partition the type, so it is inferred.

For objects the truthiness check does work, because no object is falsy.

objects.tsTypeScript
interface User {
  name: string;
}

const users: (User | undefined)[] = [{ name: "Ada" }, undefined];
const present = users.filter(u => !!u);
const list: User[] = present;
console.log(list.length);
Text
1

Here the false branch can only be undefined, since a User object is always truthy, so the partition holds and the predicate u is User is inferred. The same expression gives opposite results depending on the type of the element, and the compiler makes the right call for each.

Other guard forms

The instanceof operator, in checks and discriminant comparisons all work the same way.

forms.tsTypeScript
type Cat = { kind: "cat"; lives: number };
type Dog = { kind: "dog"; bark: boolean };
type Pet = Cat | Dog;

const pets: Pet[] = [
  { kind: "cat", lives: 9 },
  { kind: "dog", bark: true },
];

const cats = pets.filter(p => p.kind === "cat");
const lives: number = cats[0].lives;

const errors = [new Error("x"), "y", 3].filter(e => e instanceof Error);
const msg: string = errors[0].message;
console.log(cats.length, errors.length);
Text
1 1

The cats array has type Cat[], because the discriminant comparison splits the union into two exact halves. The errors array is Error[], from the instanceof check. Both rely on the same rule: the true and false branches must cover the declared type with nothing left over and nothing shared.

Where inference stops

A function with more than one parameter, a block body with several returns, or an explicit return type does not get an inferred predicate. A function that mutates its parameter does not either, because mutation could invalidate the narrowing the predicate promises. Calling another guard function inside works, because that call is itself a refinement the compiler understands. Checks that depend on run-time logic the compiler cannot see, such as a call to a custom validator that returns a plain boolean, produce no refinement, so there is nothing to infer.

When the compiler does not infer, and you know the check is right, write the predicate by hand. The compiler then trusts you.

explicit.tsTypeScript
function isPositive(n: number | undefined): n is number {
  return n !== undefined && n > 0;
}

const input: (number | undefined)[] = [1, -2, undefined, 3];
const positives = input.filter(isPositive);
const p: number = positives[0];
console.log(positives);
Text
[ 1, 3 ]

This predicate is not an iff, since -2 is a number that returns false. A hand-written predicate does not have to satisfy the condition, and the compiler accepts it. That is a hazard: in an if (!isPositive(n)) branch the compiler narrows n to undefined, which is wrong for -2. Write such predicates only when the false branch is never used for narrowing, or write the check so that it is exact.

The wrong-predicate error

The compiler does check that a predicate's type fits its parameter.

wrong.tsTypeScript
function isNumber(x: string): x is number {
  return typeof x === "number";
}
Text
wrong.ts(1,31): error TS2677: A type predicate's type must be assignable to its parameter's type.
  Type 'number' is not assignable to type 'string'.

That is the only check. The compiler does not verify that the body matches the claim, which is why hand-written predicates are a place where type safety rests on your care.

Practical guidance

For simple guards, delete the annotation and let the compiler infer. In filter and find calls, write the straightforward comparison, such as x !== null, and check the result type in your editor. If it is still wide, the guard was not an exact partition, and you should look at which value escapes: usually 0, "" or false, which the truthiness check also removes.

Keep guard functions small and single purpose. A guard that does one refinement is inferred, and a guard that mixes a type check with an unrelated condition is not. Name the function for the type it detects, so that a reader can tell what the hover shows.

Common mistakes

The first mistake is expecting filter(Boolean) or filter(x => !!x) to remove undefined from the type when the element type includes number, string or boolean. The second is adding a return type annotation to a guard and so turning inference off. The third is writing a manual predicate whose false branch is wrong and then relying on it in an else. The fourth is assuming the feature exists in older versions: projects pinned below 5.5 still need the manual predicate.

When this does not apply

Inference helps only where the compiler can see the check. Validation through a schema library, a lookup in a set, or a custom method call returns plain boolean, and the result has to be asserted with a hand-written predicate or a type assertion function. The feature also does not change run-time behaviour in any way, since predicates are erased with the rest of the types.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.