×

iFour Logo

New Features in Typescript 4.2

Kapil Panchal - January 29, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
New Features in Typescript 4.2

Microsoft recently announced the availability of TypeScript 4.2 Beta. The new version adds a number of new features and improvements to TypeScript.

What is Typescript?


TypeScript is an open-source language that is maintained and developed by Microsoft Corporation. TypeScript is primarily a superset of JavaScript that provides optional static classes, notation, and interfaces. TypeScript saves you time finding errors and providing corrections before running your code.

TypeScript 4.2 beta can be installed via NPM using the following command:

 
            npm install typescript@beta 

New features of the typescript 4.2


Rest elements in Tuple Types

Tuple types are used to model arrays of specific lengths and element types in typescript.

 
// first tuple stores the number
let arrayA: [ number, number] = [ 10, 20];
                  
// tuple stores a value that string, number and boolean
let arrayB: [ string, number, boolean ] = [ “hello”, 10, 20 ];

Tuples are more sophisticated in the typescript, as they are also using to model things like parameter lists in JavaScript. Tuples can have the rest elements and optional elements and can have the labels for readability.

 
// A tuple that has either one or two strings.
 let a: [string, string?] = ["abc"];
a = ["abc", "xyz"];
                  
  // A labeled tuple that has either one or two strings.
  let b: [first: string, second?: string] = ["hello"];
  b = ["hello", "world"];
  
  // A tuple with a *rest element* - holds at least 2 strings at the front,
  // and any number of booleans at the back.
  let c: [ string, string, ...boolean[] ];
  c = [ "hello", "world" ];
  c = [ "hello", "world", false ];
  c = [ "hello", "world", true, false, true ];

The rest elements have been specially developed so that they can be used in typescript 4.2.Typescript allowed the rest element in the last position of a tuple type in the previous versions. But in this version, the rest elements can occur at any position in the tuple with few restrictions.

 
  let a: [ ...string[], number ];

  a = [ 100 ];
  a = [ "Keval", 200 ];
  a = [ "Keval", "Maulik", "Krishna", 300 ];
  
  let b: [ boolean, ...string[], number ]; 
  b = [ true, 100 ];
  b = [ false, "Keval", 200 ];
  b = [ true, "Keval", "Aniket", "Dhruv", 300 ];

The only limitation is that a rest element can be placed anywhere in a tuple unless it is not followed by another rest element or an optional element. We can write only one rest element in a tuple.

 
   let b: [ ...number[], boolean, ...string[] ]; // rest element can not follow another rest element

   let d: [ ...number[], string? ];
   // optional element can not follow a rest element

Smarter type Alias Preservation

TypeScript has always used a series of searches to know when and how to display type aliases. The internals are smarter with the smarter type of alias preservation. A Type constructor is tracked. The language also follows type aliases of the instances of the other aliases. The ability to print the types based on the use means avoid displaying some very large types.

Template Literal Expressions have Template Literal Types

TypeScript 4.1, introduced a new type: template literal types. These types can model specific string patterns.

 
   type a = "hello" | "hi" | "sup";

   declare function Myfunction( str: `${a} ${string}`): void;
   
   // Works.
   Myfunction("hello everybody!");
   
   // Works.
   Myfunction("hi everybody!");
   
   // Error!
   // Doesn't work with the patterns:
   Myfunction("hallo everybody! Yes");

In typescript 4.2, Template string expression starts with the template types. If we assign one of these values to a mutable variable, then these types disappear and convert into a string through a process called widening.

 
  const num: number = 100;

  // Has the type `${number}px`
  const n1 = `${num}px`;
  
  // Works!
  const n2: `${number}px` = n1;
  
  // Error!
  const n3: `${number}pt` = n1;
  
  // Has the type 'string' because of widening.
  let v1 = n1;

Stricter checks for the in operator

In JavaScript, using a non-object type on the right side of the in operator is a run-time error. TypeScript 4.2 ensures that this can be captured at design time.

--noPropertyAccessFromIndexSignature:

When TypeScript first introduced index signatures, only properties declared with the "brackets" element access syntax, such as contact ["name"].

 
     interface DemoInterface {
     /** This is an index signature. */
     [Name: string]: any;
 }
 
 function doStuff(value: DemoInterface) {
     let x = value["Property"];
 }

It has become inconvenient in situations where we have to work with objects of arbitrary properties. For example, imagine an API where it is common to misspell the name of a function by adding an extra character s to the end.

 
interface Example {
// File patterns to be excluded.
exclude?: string[];

  // It handles any extra properties that we haven't declared as type 'any'.
  [x: string]: any;
}

function Options(value: Example) {
  if (value.excludes) {
      console.error("The option `excludes` is not valid !!");
  }
}

Therefore, Typescript introduces a new flag called --noPropertyAccessFromIndexSignature. In this mode, it will be enabled for inherited TypeScript behavior that generated an error. This new flag is not part of the strict flag family because we think users will find it more useful in some codebases than others.

Planning to Hire an AngularJS Development Company ? Your Search ends here.

Abstract Construct Signatures

You can pass the abstract constructors by adding the abstract modifier to a construct signal. This feature allows us to write mixin factories to support abstract classes.

 

--explainFiles:

--explainFiles flag is used to help the developers to understand why files are in the program.

 
tsc --explainFiles

When you use this option, the TypeScript compiler will give very detailed output on why a file has ended up in your program. To make it easier to read, you can export the output to a file or pipe it to a program that can easily view it.

 
tsc --explainFiles> demofile.txt

This command is useful for forwarding the output into the text file.

This is useful for pipe output to a program.

 
tsc --explainFiles | less
tsc --explainFiles | code

Conclusion


In this blog, we have seen in detail about the typescript. Microsoft recently announced the availability of TypeScript 4.2 Beta. We have seen how to install typescript and the new features of the typescript 4.2 beta.

New Features in Typescript 4.2 Microsoft recently announced the availability of TypeScript 4.2 Beta. The new version adds a number of new features and improvements to TypeScript. Table of Content 1. What is Typescript? 2. New features of the typescript 2.1. Rest elements in Tuple Types 2.2. Smarter type Alias Preservation 2.3. Template Literal Expressions have Template Literal Types 2.4. Stricter checks for the in operator 2.5. Abstract Construct Signatures 3. Conclusion What is Typescript? TypeScript is an open-source language that is maintained and developed by Microsoft Corporation. TypeScript is primarily a superset of JavaScript that provides optional static classes, notation, and interfaces. TypeScript saves you time finding errors and providing corrections before running your code. TypeScript 4.2 beta can be installed via NPM using the following command:   npm install typescript@beta New features of the typescript 4.2 Rest elements in Tuple Types Tuple types are used to model arrays of specific lengths and element types in typescript.   // first tuple stores the number let arrayA: [ number, number] = [ 10, 20]; // tuple stores a value that string, number and boolean let arrayB: [ string, number, boolean ] = [ “hello”, 10, 20 ]; Tuples are more sophisticated in the typescript, as they are also using to model things like parameter lists in JavaScript. Tuples can have the rest elements and optional elements and can have the labels for readability.   // A tuple that has either one or two strings. let a: [string, string?] = ["abc"]; a = ["abc", "xyz"]; // A labeled tuple that has either one or two strings. let b: [first: string, second?: string] = ["hello"]; b = ["hello", "world"]; // A tuple with a *rest element* - holds at least 2 strings at the front, // and any number of booleans at the back. let c: [ string, string, ...boolean[] ]; c = [ "hello", "world" ]; c = [ "hello", "world", false ]; c = [ "hello", "world", true, false, true ]; The rest elements have been specially developed so that they can be used in typescript 4.2.Typescript allowed the rest element in the last position of a tuple type in the previous versions. But in this version, the rest elements can occur at any position in the tuple with few restrictions.   let a: [ ...string[], number ]; a = [ 100 ]; a = [ "Keval", 200 ]; a = [ "Keval", "Maulik", "Krishna", 300 ]; let b: [ boolean, ...string[], number ]; b = [ true, 100 ]; b = [ false, "Keval", 200 ]; b = [ true, "Keval", "Aniket", "Dhruv", 300 ]; The only limitation is that a rest element can be placed anywhere in a tuple unless it is not followed by another rest element or an optional element. We can write only one rest element in a tuple. Read More: The Most Popular Frameworks - Angular, React And Vue   let b: [ ...number[], boolean, ...string[] ]; // rest element can not follow another rest element let d: [ ...number[], string? ]; // optional element can not follow a rest element Smarter type Alias Preservation TypeScript has always used a series of searches to know when and how to display type aliases. The internals are smarter with the smarter type of alias preservation. A Type constructor is tracked. The language also follows type aliases of the instances of the other aliases. The ability to print the types based on the use means avoid displaying some very large types. Template Literal Expressions have Template Literal Types TypeScript 4.1, introduced a new type: template literal types. These types can model specific string patterns.   type a = "hello" | "hi" | "sup"; declare function Myfunction( str: `${a} ${string}`): void; // Works. Myfunction("hello everybody!"); // Works. Myfunction("hi everybody!"); // Error! // Doesn't work with the patterns: Myfunction("hallo everybody! Yes"); In typescript 4.2, Template string expression starts with the template types. If we assign one of these values to a mutable variable, then these types disappear and convert into a string through a process called widening.   const num: number = 100; // Has the type `${number}px` const n1 = `${num}px`; // Works! const n2: `${number}px` = n1; // Error! const n3: `${number}pt` = n1; // Has the type 'string' because of widening. let v1 = n1; Stricter checks for the in operator In JavaScript, using a non-object type on the right side of the in operator is a run-time error. TypeScript 4.2 ensures that this can be captured at design time. --noPropertyAccessFromIndexSignature: When TypeScript first introduced index signatures, only properties declared with the "brackets" element access syntax, such as contact ["name"].   interface DemoInterface { /** This is an index signature. */ [Name: string]: any; } function doStuff(value: DemoInterface) { let x = value["Property"]; } It has become inconvenient in situations where we have to work with objects of arbitrary properties. For example, imagine an API where it is common to misspell the name of a function by adding an extra character s to the end.   interface Example { // File patterns to be excluded. exclude?: string[]; // It handles any extra properties that we haven't declared as type 'any'. [x: string]: any; } function Options(value: Example) { if (value.excludes) { console.error("The option `excludes` is not valid !!"); } } Therefore, Typescript introduces a new flag called --noPropertyAccessFromIndexSignature. In this mode, it will be enabled for inherited TypeScript behavior that generated an error. This new flag is not part of the strict flag family because we think users will find it more useful in some codebases than others. Planning to Hire an AngularJS Development Company ? Your Search ends here. See here Abstract Construct Signatures You can pass the abstract constructors by adding the abstract modifier to a construct signal. This feature allows us to write mixin factories to support abstract classes.   --explainFiles: --explainFiles flag is used to help the developers to understand why files are in the program.   tsc --explainFiles When you use this option, the TypeScript compiler will give very detailed output on why a file has ended up in your program. To make it easier to read, you can export the output to a file or pipe it to a program that can easily view it.   tsc --explainFiles> demofile.txt This command is useful for forwarding the output into the text file. This is useful for pipe output to a program.   tsc --explainFiles | less tsc --explainFiles | code Conclusion In this blog, we have seen in detail about the typescript. Microsoft recently announced the availability of TypeScript 4.2 Beta. We have seen how to install typescript and the new features of the typescript 4.2 beta.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

An in-depth guide on Angular Dependency Providers
An in-depth guide on Angular Dependency Providers

What is Angular? Angular is a frontend development framework used for building single-page client applications using HTML and Typescript. It is written in Typescript. What...

A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe
A simple guide to Build Angular Reactive Templates with Ngif and Async Pipe

Angular Templates seamlessly help to expedite the development process with flawless assistance of components and other specific elements. These are dynamic and renders according...

A simple guide on AOT Compilation in Angular
A simple guide on AOT Compilation in Angular

What is a Compiler? A compiler is nothing but a part of code that converts one programming language to another. If we talk about some simple programming languages like C, C++,...