TypeScript 4.5 Features Overview

Image by Martyn Cook from Pixabay

Microsoft recently released TypeScript 4.5 with a new utility type – Awaited and Promise improvements for enhancing asynchronous programming.

To get started with this new version, developers can install it using the following command:

npm install typescript

One thing to note is that TypeScript 4.5 doesn’t support ECMAScript module support for Node.js 12, which has been deferred since the beta release.

Let’s see what we get in this new version in brief:

The Awaited Type and Promise Improvements

Awaited type is meant to model operations like await in async functions, or the .then() method on Promises.

The Awaited type can be helpful for modeling existing APIs, including JavaScript built-ins like Promise.allPromise.race,

Supporting lib from node_modules

TypeScript 4.5 introduces a way to override a specific built-in lib. For example, If you wanted to lock your project to a specific version of the DOM APIs, you could add this to your package.json. Then even if you update TypeScript 4.5 onwards, your dependency manager will ensure that the same version of DOM API is used.

Template String Types as Discriminants

TypeScript 4.5 now can narrow values that have template string types, and also recognizes template string types as discriminates. You can check more details here.

–module es2022

TypeScript 4.5 supports new module settings: es2022. This means you can use await outside of async function.

Disabling Import Elision

There are some cases where TypeScript can’t detect that you’re using an import. In such scenarios, typescript will remove imports by default. But in TypeScript 4.5 you can use –preserveValueImports to prevent TypeScript from removing imports.

Private Field Presence Checks

TypeScript 4.5 supports an ECMAScript proposal for checking whether an object has a private field on it. You can now write a class with a #private field member and see whether another object has the same field by using the in operator.

Import Assertions

It will ensure that an import has an expected format. See the below example from Microsoft Blog.

import obj from "./something.json" assert { type: "json" };

Faster Load Time with realpathSync.native

TypeScript now leverages the realpathSync.native function in Node.js on all operating systems.

Previously this function was only used on Linux, but in TypeScript 4.5, as long as you’re running a recent-enough version of Node.js. This change sped up project loading by 5-13% on certain codebases on Windows.

Apart from the above changes, following are the additional changes which you can see in this new release.

You can also check TypeScript 4.6 milestone here! Yes! you read it right. Microsoft team is already working on TypeScript 4.6.

Leave a Reply

Your email address will not be published. Required fields are marked *