Optional chain combined with a null value

TypeScript 3.7 key features explained

Ts reason to upgrade to version 3.7, because 3.7 has several important features can improve development efficiency

Optional chain

Use?. Operator for optional attributes access

let x = foo?.bar.baz();

When defined foo, calculated foo.bar.baz (); if foo is null or undefined, the program will stop and return only undefined. An equivalent code above the following wording:

let x = (foo === null || foo === undefined) ?
    undefined :
    foo.bar.baz();

Note that if the bar is null or undefined, our code will still be an error when accessing baz. Similarly, if baz is null or undefined, when we call the function will error. ?. Only check its value on the left side is null or undefined, without checking any subsequent property.

You may be used? Alternatively code uses many intermediate properties && operator performs checking.

// 之前
if (foo && foo.bar && foo.bar.baz) {
    // ...
}

// 之后
if (foo?.bar?.baz) {
    // ...
}

Chain optionally further comprises two other operations. The first is access to an optional element, which acts like an optional attribute access, but allows us access to the non-identifier attribute (e.g., arbitrary string, numerals and symbols):

/**
 * 当我们有一个数组时,返回它的第一个元素
 * 否则返回 undefined。
 */
function tryGetFirstElement<T>(arr?: T[]) {
    return arr?.[0];
    // 等效:
    // return (arr === null || arr === undefined) ?
    // undefined :
    // arr[0];
}

Another alternative is called, if the expression is not null or undefined, we can call them conditionally.

async function makeRequest(url: string, log?: (msg: string) => void) {
    log?.(`Request started at ${new Date().toISOString()}`);
    // 等效:
    // if (log !== null && log !== undefined) {
    // log(`Request started at ${new Date().toISOString()}`);
    // }

    const result = (await fetch(url)).json();

    log?.(`Request finished at at ${new Date().toISOString()}`);

    return result;
}

Null merger

Use as ?? null coalescing operator

E.g:

let x = foo ?? bar();

This is a new approach will be used to represent the value foo "present"; but when it is, it is calculated to null or undefined in its position bar ().

Similarly, the above code is equivalent to the following wording.

let x = (foo !== null && foo !== undefined) ?
    foo :
    bar();

When trying to use the default values, the operator can replace ?? ||. For example, the following code fragment attempts to obtain volume value last saved in local-Storage (if ever saved), but because it uses ||, so the error.

function initializeAudio() {
    let volume = localStorage.volume || 0.5

    // ...
}

LocalStorage.volume When set to 0, the page unexpectedly volume to 0.5. ?? can avoid 0, NaN, and "some unexpected behavior" are treated as false values.

pay attention

Since the introduction of typescript 3.7.2, type checking when will report / element-ui / types / cascader.d.ts a node_modules
error in the file, find the file,

import { CascaderOption, CascaderProps, CascaderNode } from './cascader-panel';

Add a row before

// @ts-ignore

Guess you like

Origin www.cnblogs.com/dshvv/p/12044649.html