3

If you have dreams and dry goods, search for [Moving to the World] still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

Today, I will introduce some of the newer features and developments of TypeScript. These are the features that 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 take a look at the early practices:

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;
    
  }
}

Use the abbreviated grammar in ts:

class Note {
  constructor(
     public title: string, 
     public content: string, 
     private history: string[]
  ){
    // 这里不用在写 this.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 the parameters of the constructor.

This shorthand syntax does a lot:

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

Null merge

?? is actually meaningless, it is Nullish Coalescing (Nullish Coalescing). It sounds a bit ignorant, let's go directly to the code

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

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

At this time, you definitely want to say that this is not the end?

let k = i || 5

Although this is also useful, don't you think it is not rigorous? What if i = 0 ?

Private class field

TypeScript 3.8 will support ECMAScript private fields, don't confuse it with the TypeScript private modifier.

This is the class with private class fields in TypeScript:

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

private keyword is that the former has better runtime guarantees. The TypeScript field declared with the private will become a regular field in the compiled JavaScript code. On the other hand, private class fields are still private in the compiled code.

Attempting to access private class fields at runtime will result in a syntax error. We also use browser development tools and cannot check private class fields.

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

Labeled tuple types

The named tuple type is suitable for TypeScript 4.0 and above to be used. It greatly improves our development experience and efficiency. Let’s look at an example first:

type Address = [string, number]

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

When we define the function to enter the parameters in this way, when using the function, the editor's smart prompt will only remind us of the parameter type, losing the description of the meaning of the parameter.

image.png

In order to improve this, we can use Labeled tuple types, we can define parameters like this:

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

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

image.png

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 use the feature of Template Literals to write strings with backticks instead of single quotes or double quotes:

const message = `text`;

As Flavio Copes said, template literals provide features that were not available in previously quoted strings:

  • It is very convenient to define multi-line strings
  • Can easily interpolate variables and expressions
  • You can use template tags to create DSL (Domain Specific Language, domain specific language)

The template literal type is exactly the same as the template string syntax in JavaScript, except that it is used in the type definition:

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

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

image.png

When we define a specific literal type, TypeScript will generate a new string literal type by splicing content.

Practical 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, capitalizing letters, or making all attributes optional.

The following is an Omit tool, which replicates all the attributes of the original type, except for those we chose not to include.

image.png

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

type MyUser = Omit<User, 'name'>

The above are some of the parts I often use in my work, and the others will be shared later, just this?

~End, I’m Shuawanzhi, I’m going to make noisy chicken to eat, we will see you in the next issue.

code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .

comminicate

There are dreams and dry goods. WeChat search [Moving to the World] pay attention to this brushing wit who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68.2k 声望105k 粉丝