These six new TS features are often used, and I can’t live without them anymore!

Time:2022-7-2

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq449245884/xiaozhiIt has been included, and there are complete test sites, materials and my series of articles for the interview of front-line big factories.

Today, let’s introduce some new functions and developments of typescript, which I often use in my daily work.

Define attributes directly in the constructor

In typescript, attributes can be defined directly through the parameters of the constructor. Let’s look at the early practice first:

class Note {
  public title: string;
  public content: string;
  private history: string[];
  
  constructor(title: string, content: string, history: string[]) {
    this.title = title;
    this.content = content;
    this.history = history;
    
  }
}

Adopt the abbreviation syntax in TS:

class Note {
  constructor(
     public title: string, 
     public content: string, 
     private history: string[]
  ){
    //Don't write this here title = title
  }
}

It may not look like a class with attributes, but it does, using the shorthand form provided by typescript – defining attributes directly with constructor parameters.

This shorthand grammar does a lot:

  • Declares a constructor parameter and its type
  • Declared a public attribute with the same name
  • When we new an instance of this class, initialize the attribute to the corresponding parameter value

Null value consolidation

??In fact, it’s meaningless, that is, null coalescing. It sounds a little confused. Let’s go directly to the code

const i = undefined
const k = i ?? 5
console.log(k) // 5

//3.9.2 compilation
const i = undefined;
const k = i !== null && i !== void 0 ? i : 5;
console.log(k); // 5

At this time, you must want to say, isn’t it over?

let k = i || 5

Although it works like this, don’t you think it’s not rigorous? Ifi = 0And?

Private class fields

Typescript 3.8 will support ECMAScript private fields, which must not be confused with the typescript private modifier.

This is a class with private class fields in typescript:

class Animal {
  #name: string;
  constructor(theName: string) {
    this.#name = theName;
  }
}

stayprivateThe difference between using private class fields over keywords is that the former has better runtime assurance. useprivateThe typescript field declared by the keyword will become a regular field in the compiled JavaScript code. On the other hand, private class fields are still private in compiled code.

Attempting to access private class fields at run time will result in a syntax error. We can’t check private class fields with browser development tools.

With private class fields, we finally get real privacy in JavaScript.

Labeled tuple types

Named tuple types can only be used with typescript version 4.0 or above, which greatly improves our development experience and efficiency. Let’s take a look at an example first:

type Address = [string, number]

function setAddress(...args: Address) {
  // some code here
  console.log(args)
}

When we define the function parameters in this way, when using the function, the intelligent prompt of the editor will only prompt us the parameter type, and the description of the parameter meaning is lost.

These six new TS features are often used, and I can't live without them anymore!

To improve this, we can use labeled tuple types to define parameters as follows:

type Address = [streetName: string, streetNumber: number]

function setAddress(...args: Address) {
  // some code here
  console.log(args)
}

These six new TS features are often used, and I can't live without them anymore!

In this way, when calling the function, our parameters get the corresponding semantics, which makes the code easier to maintain.

Template literal type

Since ES6, we can write strings with inverted quotation marks through the feature of template literals, not just single quotation marks or double quotation marks:

const message = `text`;

As Flavio copes said, template literals provide features that previous strings written in quotation marks do not have:

  • Defining multiline strings is very convenient
  • You can easily interpolate variables and expressions
  • DSL (domain specific language) can be created with template tags

The template literal type is completely consistent with the template string syntax in JavaScript, but it is used in the type definition:

type topBottom = "top" | "bottom"
type leftRight = "left" | "right"

type Position = `${topBottom }-${leftRight }`

These six new TS features are often used, and I can't live without them anymore!

When we define a specific literal type, typescript will produce a new string literal type by splicing content.

Utility type

Typescript provides you with a set of practical types, allowing you to build new types on the basis of existing types. There are many practical types that cover different situations, such as selecting type attributes to copy, uppercase letters, or making all attributes optional.

The following is a useOmitTool example, which copies all the attributes of the original type, except those we chose not to include.

These six new TS features are often used, and I can't live without them anymore!

type User = {
  name: string
  age: number
  location: string
}

type MyUser = Omit<User, 'name'>

These are the parts I often use in my work. Others will be shared later. Is that it?

~After that, I’m washing the bowl and ready to quarrel with the chicken. I’ll see you next time.

We can’t know the bugs that may exist after the code is deployed in real time. In order to solve these bugs afterwards, we spent a lot of time on log debugging. By the way, we recommend a useful bug monitoring toolFundebug

communication

Dream, dry goods, wechat search[move to the world]Pay attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHubhttps://github.com/qq44924588…It has been included, and there are complete test sites, materials and my series of articles for the interview of front-line big factories.

These six new TS features are often used, and I can't live without them anymore!