A brief discussion of 3 new features worth noting in TypeScript 3.7

A brief discussion of 3 new features worth noting in TypeScript 3.7

Preface

It has been a while since TypeScript 3.7 was officially released. During this period, I am migrating my current project to TypeScript, so I will pay special attention to every release.

As for the new features included in 3.7, it is actually a relatively small release compared to the previous releases, but the several features included in it will bring significant improvements to the code quality itself.

Optional Chaining

The first feature is the support for the optional chaining operator, which should be translated as the optional chaining operator. Of course, I still think this translation is a bit strange, so let’s just use English for now.

This feature is first of all a new feature included in es2019. For the feature itself, those who are interested can refer to here.

Since TypeScript is a superset of JavaScript, it is expected that this feature will be implemented in advance. The usage is roughly as follows:

a?.b();

is equivalent to:

if(a) ab();
// or a && ab()

If it is multi-layer nesting, for example, b is also an object, and you want to continue calling c(), you can do it like this:

a?.b?.c()

But even if it is written like this, it is not safe, because the b in b() may also be a null value, and an exception will be thrown if it is called directly. For absolute safety, you can write:

a?.b?.();

It is worth noting that we must have a correct understanding of the meaning of optional here. Optional means that it is modified by ? in the type declaration, indicating that a type contains a property that can be nullable. What this means is that ?. will not be called on properties that do not conform to the type declaration itself, for example:

interface A {}

const a: A = {};

a?.b?.(); // Property 'b' does not exist on type 'A'

Unless the declaration of interface A is changed to:

interface A {
  b?: any
}

This feature has great practical significance in the project. We can write fewer if assertion statements or && operators, but achieve the same effect.

Nullish Coalescing

Translated from Chinese, it is called the double question mark operator, which is actually quite descriptive because its syntax is exactly ??.

The function of this operator, to put it simply, is to specify a default value for a null value, similar to the following code:

let a = b || 'foo'

When b is null, due to the nature of the || operator, the value of a will be assigned to foo. If we use the ?? operator to rewrite it, it would look like this:

let a = b ?? 'foo'

On the surface, there seems to be no difference between the two, but there is actually a hidden problem here, that is, the concept of null value does not only refer to null and undefined, but also a series of logically false values ​​such as false and 0 are counted as null values, which is obviously problematic, for example:

const b = 0
let a = b || 'foo'
// a is 'foo'

In this example, we expect a to be assigned a default value only when b is a truly empty value (null or undefined). a should be equal to 0, but the actual running result is foo, because b = 0, which will be interpreted as false during the operation of the || operator. I once wrote a verification code component in an actual project. Unfortunately, I fell into this pit and spent a long time debugging this problem.

But using the ?? operator, this problem does not exist.

Uncalled Function Checks

I believe many people have encountered similar problems. Due to the lack of effective naming conventions, assertion attributes and assertion methods are mixed in actual projects, such as:

class A {
    isFoo(): boolean {
        return false;
    }
}

function test(a: A) {
    if (a.isFoo) { 
        ...
    } 
}

Here, if our intention is to get an assertion value by calling a.isFoo, we have obviously made a mistake. We should use if (a.isFoo()) instead of directly if (a.isFoo), because although the latter is not wrong at the syntactic level, it will be asserted as true in logical meaning. But after the release of 3.7, TypeScript will try to help us find this problem.

Despite this, I still recommend that you develop a unified naming convention for assertion methods and assertion attributes, such as isXXX for attributes and assertXXX for methods.

other

Some other changes are changes in usability, such as:

  • Flatter Error Reporting: It will compress a large section of repeated error logs into a single, more accurate, and more concise error log as much as possible.
  • @ts-nocheck at the file level: In previous versions, this annotation only supported the inline level
  • Recursive type declaration: You can use recursive syntax in type declaration to declare more complex types, such as json type
  • Provide declaration support for js files to reduce the migration cost from js projects

The above is a brief discussion of the details of three new features worth noting in TypeScript 3.7. For more information about the new features of TypeScript 3.7, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • In-depth understanding of the use of the infer keyword in typescript
  • Why TypeScript's Enum is problematic
  • A tutorial on how to install, use, and automatically compile TypeScript
  • Vue's new partner TypeScript quick start practice record
  • How to limit the value range of object keys in TypeScript
  • Explain TypeScript mapped types and better literal type inference
  • Detailed explanation of TypeScript 2.0 marked union types
  • TypeScript function definition and use case tutorial

<<:  Detailed tutorial on installing Nginx 1.16.0 under Linux

>>:  Detailed explanation of the method of comparing dates in MySQL

Recommend

Analysis of Mysql data migration methods and tools

This article mainly introduces the analysis of My...

MySQL 8.0.12 installation and configuration graphic tutorial

Recorded the download and installation tutorial o...

Dynamically edit data in Layui table row

Table of contents Preface Style Function Descript...

Linux installation MySQL tutorial (binary distribution)

This tutorial shares the detailed steps of instal...

This article helps you understand PReact10.5.13 source code

Table of contents render.js part create-context.j...

CentOS 8.0.1905 installs ZABBIX 4.4 version (verified)

Zabbix Server Environment Platform Version: ZABBI...

HTML 5.1 learning: 14 new features and application examples

Preface As we all know, HTML5 belongs to the Worl...

Disabled values ​​that cannot be entered cannot be passed to the action layer

If I want to make the form non-input-capable, I se...

WeChat applet implements a simple handwritten signature component

Table of contents background: need: Effect 1. Ide...

A brief analysis of whether using iframe to call a page will cache the page

Recently, I have a project that requires using ifr...

Detailed explanation of Apache SkyWalking alarm configuration guide

Apache SkyWalking Apache SkyWalking is an applica...

Detailed examples of Linux disk device and LVM management commands

Preface In the Linux operating system, device fil...