×

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.

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. 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. 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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

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
Next-Gen Programming Languages: Shaping the Future of Software Development in 2024
Next-Gen Programming Languages: Shaping the Future of Software Development in 2024

Introduction Imagine standing in line at the grocery store, waiting to pay for groceries. You pull out your phone and scan each item’s barcode with a single tap. This seemingly...

20 Essential DevOps Tools That Businesses Should Embrace In 2024
20 Essential DevOps Tools That Businesses Should Embrace In 2024

Before navigating into the world of DevOps, it's important to know what DevOps is exactly. DevOps is a methodology that uses continuous integration, continuous delivery, and automation to shorten the software delivery lifecycle (SDLC). More than just a set of practices, DevOps embodies a culture and a philosophy that bridges the gap between developers (Dev) and IT operations (Ops) teams.

Microsoft PowerApps Development: Is It A Low-Code Or No-Code Approach
Microsoft PowerApps Development: Is It A Low-Code Or No-Code Approach

Microsoft PowerApps has become the preferred digital solution, particularly for non-tech clients. It is a simple and easy-to-use app development platform that does not require much coding and can help you create personalized apps effortlessly with drag-and-drop capabilities.