TypeScript’s control flow analysis does a great job of tracking how the type of a variable changes as it moves through your code: In the past, t

Announcing TypeScript 5.5 Beta

submited by
Style Pass
2024-04-25 22:30:06

TypeScript’s control flow analysis does a great job of tracking how the type of a variable changes as it moves through your code:

In the past, this sort of type refinement was more difficult to apply to arrays. This would have been an error in all previous versions of TypeScript:

This code is perfectly fine: we’ve filtered all the undefined values out of the list. But TypeScript hasn’t been able to follow along.

This works because TypeScript now infers a type predicate for the filter function. You can see what’s going on more clearly by pulling it out into a standalone function:

bird is Bird is the type predicate. It means that, if the function returns true, then it’s a Bird (if the function returns false then it’s undefined). The type declarations for Array.prototype.filter know about type predicates, so the net result is that you get a more precise type and the code passes the type checker.

Previously, TypeScript would have just inferred that these functions return boolean. It now infers signatures with type predicates like x is number or x is NonNullable<T>.

Leave a Comment