TypeScript soothes type narrowing pain point

By Paul Krill

TypeScript 5.4, a planned update to the strongly typed JavaScript variant from Microsoft, has graduated to the release candidate stage. New capabilities in version 5.4 include preserved narrowing within function closures created after the last assignment and a NoInfer type to block inferences to valid but unwanted types.

The release candidate was published February 22, following a beta release from January 29. A final release is expected March 5. TypeScript 5.4 can be accessed via NuGet or NPM. In NPM, use the following command:

npm install -D typescript@rc

Since the beta release, release notes have been updated to document notable behavioral changes including restrictions around enum capabilities, improvements in mapped type behavior, and restrictions on enum member naming.

Detailing the type narrowing improvement, Microsoft said a common pain point in TypeScript was that narrowed types were not always preserved within function closures. In TypeScript 5.4, when parameters and let variables are used in non-hoisted functions, the type checker will look for a last assignment point. If one is found, TypeScript can narrow from outside the containing function.

TypeScript 5.4 also introduces a NoInfer<T> utility type. Surrounding a type in NoInfer<…> gives a signal to TypeScript to match the inner types to find candidates for type inference. The utility type addresses an issue in which TypeScript can infer type arguments from whatever is passed in. But it is not always clear what is the best type to infer, leading TypeScript to reject valid calls and make other mistakes.

Other improvements in TypeScript 5.4:

TypeScript 5.4 follows predecessor TypeScript 5.3, released in November 2023 and featuring import attributes for ECMAScript modules.

© Info World