11
头图

Remember what I mentioned in the "Summary of the State of JavaScript Research Report 2020" which is the most popular JavaScript written by global developers in 2020? - That's right! TypeScript ! . In view of the use of TypeScript in the project does have the following benefits:

  1. Help developers to timely perceive type/syntax errors at "code writing" (in conjunction with the editor) instead of "code runtime" (⚠️ Note that TypeScript is not a panacea, it does not help you catch request errors or environmental errors);
  2. Combined with the editor, provide intelligent prompts to enhance the development experience;
  3. One point that is rarely mentioned: it is easier for server-side programmers to understand the code and facilitate front-end and back-end communication;

This article will introduce you to some practical features of TypeScript updated since version 3.7. I hope your code can become more stable and elegant.

1. New Support Features

Please note that TypeScript is a superset of JavaScript types, not a superset of syntax. Therefore, some codes that conform to JavaScript syntax specifications may report errors in TypeScript, for example:

let x = 1
x = 'hello world'

Therefore, in modern tool chains, the TypeScript compiler is not even used as a tool to compile a specific version of JavaScript (this is usually the job of babel), but as a more powerful code inspection tool. However, with the update of the TypeScript version, some new JavaScript syntax features are gradually supported by TypeScript, which allows developers to get rid of the babel compilation process in some scenarios and directly use TypeScript to compile and generate the final code.

1.1 Optional Chaining & Nullish Coalescing

Since version 3.7, TypeScript supports Optional Chaining and Nullish Coalescing currently in stage 4.

1.2 Private Fields && Namespace exports

Since version 3.8, Typescript supports the Private Fields grammar currently in stage 3. (Using the WeakMap data structure at the bottom, this syntax makes the JavaScript class truly have "private properties")

class Foo {
  #bar
}

At the same time, this version also supports namespace exports syntax:

export * as utils from './utils'

1.3 Inference of class field types

Since version 4.0, TypeScript supports automatic deduction of the attribute types in the class, no need to display the declaration.


2. New type: tuple

TypeScript 4.0 began to support two new tuple type declaration methods:

  1. Variadic tuple types
  2. Labeled tuple types

2.1 Variable tuple types

type Foo<T extends any[]> = [boolean, ...T, boolean]

In this way of declaration, we can define a function parameter type more precisely. This way of definition is very useful when using functional programming.

2.2 Named tuple types

const Address = [string, number]

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

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. In order to improve this, we can use Labeled tuple types, we can define parameters like this:

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

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

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


3. Recursive call type

Since Typescript 3.7, we finally gained the ability to declare JSON data with only one type declaration:

type JSONValue = 
  | string
  | number
  | boolean
  | null
  | JSONValue[]
  | {
      [key: string]: JSONValue
    }

4. Error and assertion handling

4.1 // @ts-expect-error

TypeScript 3.9 gives an alternative to // @ts-ignore comments: // @ts-expect-error .

Literally, it is not difficult to understand why the latter is the better choice:

  1. Show that the reason for the error will be reported, not just blindly circumvent the inspection;
  2. Forward compatibility. In the future, if TypeScript supports a certain grammar and no more errors are reported, TypeScript will actively prompt to delete comments, which will make the code more concise;

4.2 unknown type

Let's think about what this code will eventually print:

try {
  willThrowAnError()
} catch (err) {
  console.log(typeof err.message)
}

Is the answer "string" , not so! Because err.message value is likely to be undefined , and may even be in here throwing error, depending on our function willThrowAnError how the interior is defined by:

// err.message => undefined
function willThrowAnError() {
    throw 'hello world'
}

// err.message => throw an Error!
function willThrowAnError() {
  throw null
}

Although the second case almost never happens, these two examples illustrate the catch parameter type of 060a156a34c9c6 (so in TypeScript, its default type is any ).

Therefore, in TypeScript 4.0, the unknown type is provided for us to deal with these types that we "don't know". Different from the any type, unknown is the first type in TypeScript and can be used anywhere.

The son said: Knowing is knowing, not knowing is not knowing.

4.3 Assertion functions

Since TypeScript 3.7, type assertions return/throw

function assertIsArray(val: any): asserts val is any[] {
  if (!Array.isArray(val)) throw new Error(`${val} is not an array`)
}

This will make testing easier.

Click here to view related documents


5. Module

5.1 Type-only imports

Since TypeScript 3.8, TypeScript supports only the introduction of module types:

import type { SomeThing } from "./some-module.js";

export type { SomeThing };

The advantage of this is that when a module contains side-effect code, if the user directly introduces the module, the side-effect code will be executed unintentionally, but when only the type is introduced through the declaration, this hidden danger is avoided.

Click here to view related documents .

6. Summary

So far, this article has taken you to quickly browse some practical new features since TypeScript 3.7. I wonder if you have learned something? TypeScript will release version 4.3 on May 25, 2021. What interesting new features will be added by then? Let’s listen to the next breakdown:)


libinfs
1.7k 声望2.5k 粉丝

🚀 Web应用设计师 & 开发工程师 | 🎸 吉他爱好者 | 📚 终生学习者 | ✨ 极简主义信仰者 | ✍️ 科技专栏作家 | 🎨 图形学新手 | 🔍 AI技术狂热追踪者