Inferred Type Predicates
It's finally here! While working with TypeScript, I assume we all have been in a situation where we have to write a type predicate to help TypeScript...
It's finally here! While working with TypeScript, I assume we all have been in a situation where we have to write a type predicate to help TypeScript understand the type of a variable. For most cases this is fine, but it can be a pain to write these while using the filter method.
Now with the TypeScript 5.5 release, TypeScript introduces a new feature called Inferred Type Predicates. This feature allows TypeScript to infer type predicates automatically. This means that TypeScript can now understand the type of a variable or return value based on the conditions that are checked in the code.
Functions that previously required a Type Predicate can now be simplified. This is a great improvement for developers, as it reduces the amount of boilerplate code needed to write type predicates.
type Person = { name: string };const persons: (Person | null)[] = [];const personNames = persons.filter((person) => !!person).map((person) => person.name); // ^? Person
type Person = {name:string};const persons: (Person|null)[] = []const personNames = persons.filter(person => !!person).map(person => person.name)~~~~~~ 'person' is possibly 'null'.// ^? Person | null
Take a look at the following TypeScript playground examples to see the difference between TypeScript 5.5.0-beta and TypeScript 5.4.5.
Additional resources
- Announcing TypeScript 5.5 RC by Daniel Rosenwasser - the official announcement of the feature
- The Making of a TypeScript Feature: Inferring Type Predicates by Dan Vanderkam - why and how Dan implemented this feature
- Type Predicate Inference: The TS 5.5 Feature No One Expected by Matt Pocock - a detailed explanation of the feature (with examples)
Feel free to update this developer bit on GitHub, thanks in advance!