current position:Home>Six new typescript features frequently used

Six new typescript features frequently used

2021-08-27 03:18:29 I planted the sun

Define the property directly in the constructor

Typescript Properties 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;
 Copy code 

use ts Simplified grammar in :

class Note {
  constructor( public title: string, public content: string, private history: string[] ){
    //  There's no need to write  this.title = title
 Copy code 

It may not look like a class with attributes , But it does have , Use of is Typescript Short form provided — Define properties 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 When an instance of this class , Initialize the attribute to the corresponding parameter value

Null merge

It's not really interesting , Namely Nullish Coalescing ( Null merge ). Sounds a little confused , Let's go straight to the code

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

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

At this time, you must want to say, so it's over ?

let k = i || 5
 Copy code 

Although it also uses , But don't you think it's not rigorous ? If i = 0 Well ?

Private class fields

TypeScript 3.8 Will support ECMAScript Private field , Never talk to TypeScript private Modifier confusion .

This is TypeScript Class with private class field in :

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

stay private The difference between using private class fields over keywords is that the former has better runtime guarantee . use private Keyword declared TypeScript The field will be in the compiled JavaScript Become a regular field in the 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 also use browser development tools, and we can't check private class fields .

With private class fields , We finally JavaScript Get real privacy .

Named tuple type (Labeled tuple types)

Named tuple types are appropriate TypeScript 4.0 And above versions can be used , It has greatly improved our development experience and efficiency , Let's start with an example :

type Address = [string, number]

function setAddress(...args: Address) {
  // some code here
 Copy code 

When we define a function as a parameter in this way , When using functions , The intelligent prompt of the editor will only prompt us the parameter type , Missing description of parameter meaning .


To improve this , We can go through Labeled tuple types, We can define parameters like this :

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

function setAddress(...args: Address) {
  // some code here
 Copy code 

bVcT9Fo.webp such , When the function is called , Our parameters get the corresponding semantics , This makes the code easier to maintain .

Template literal type

since ES6 Start , We can use the template literal (Template Literals) Characteristics of , Write a string in backquotes , Not just single or double quotes :

const message = `text`;
 Copy code 

just as Flavio Copes What I have said , Template literals provide features that strings previously written in quotation marks do not have :

  • Defining multiline strings is very convenient
  • You can easily interpolate variables and expressions
  • You can use template tags to create DSL(Domain Specific Language, Domain specific language )

Template literal type and JavaScript The template string syntax in is exactly the same , It's just used in type definitions :

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

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

bVcT9FH.webp When we define a specific literal type ,TypeScript A new string literal type will be generated by splicing content .

Utility type

TypeScript Provides you with a set of utility types , Let you build new types based on existing types . There are many utility types that cover different situations , For example, select a type attribute to copy , Capital , Or make all attributes optional .

Here is a use  Omit Examples of tools , It copies all the properties of the original type , Except for those we choose not to include .


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

type MyUser = Omit<User, 'name'>
 Copy code 

copyright notice
author[I planted the sun],Please bring the original link to reprint, thank you.

Random recommended