TypeScript 4.4 is available in Release Candidate version

On August 12, Microsoft announced the availability of Typescript 4.4 as a Release Candidate. This new version of the language mainly brings a better analysis of the control flow of alias conditions and the introduction of the flag –useUnknownInCatchVariables

Alias ​​condition control flow analysis

In JavaScript, we often have to probe a variable in different ways to see if it has a more specific type that we can use. TypeScript understands these checks and calls them type guards. Instead of having to convince TypeScript of the type of a variable every time we use it, the type checker exploits what is called thecontrol flow analysis to deduce the type in each language construct.

For example :

function foo (arg: unknown) {
if (typeof arg === “string”) {
// We know this is a string now.
console.log (arg.toUpperCase ());

But what happens in the following case that moves the condition to a constant:

function foo (arg: unknown) {
const argIsString = typeof arg === “string”;
if (argIsString) {
console.log (arg.toUpperCase ());
// ~~~~~~~~~~~
// Error! Property ‘toUpperCase’ does not exist on type ‘unknown’.

TypeScript has lost the type information and is reporting an error.

TypeScript 4.4 has better parsing and the code below now works without errors.

The –useUnknownInCatchVariables flag

In JavaScript, any type of value can be thrown with throw and captured in a catch clause. For this reason, TypeScript historically typed catch clause variables as any, and did not allow any other type annotation:

try {
// Who knows what this might throw …
executeSomeThirdPartyCode ();
catch (err) {// err: any
console.error (err.message); // Allowed, because ‘any’
err.thisWillProbablyFail (); // Allowed, because ‘any’ 🙁

However, when TypeScript added the type unknown, it became clear that this was a better choice than any in catch clause variables for users who want the highest degree of accuracy and type security.

Finally, TypeScript 4.0 allowed users to specify an explicit type unknown (or any) annotation on each catch clause variable. However, manually specifying each clause can quickly become a chore.

Therefore, TypeScript 4.4 introduces a new flag called –useUnknownInCatchVariables. This flag changes the default type of clause variables from any to unknown

This flag is enabled under the –strict family of options. This means that if you verify your code using –strict, this option will be automatically enabled.

To use typescript 4.4 RC you can get it through NuGet or use npm with the following command:

npm install typescript @ rc

Back to top button