Optional chaining and null coalescing in typescript
Liu wayong 2021-06-14 04:42:45

Optional Chaining The problem is repeated and meaningless empty , It's meaningless , Yes, it's not necessary for the business , But not empty , The program just hung up , such as :

let x = foo.bar.baz();
 

On the access link here foo bar baz Any one for undefined, The program stops working .

Use Optional Chaining After modification :

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

here ?. The syntax of is Optional Chaining, stay TypeScript 3.7 To realize , at present tc39 The position in the proposal is Stage 4 Stage .

Optional Chaining Here it means , If foo yes null or undefined, The entire statement does not continue to be executed later , Go straight back to undefined.

Scope of action

It should be noted that , Here only for foo It's guaranteed , If the following bar,baz Empty words , The code still reports an error .?. Only the objects on the left .

So you can fix it like this :

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

This can guarantee foo bar If it is empty, no error will be reported . This is reflected. optional property accesses The function of .

Opptoinal call

The same applies to methods .

async function makeRequest(url: string, log?: (msg: string) => void) {
log?.(`Request started at ${new Date().toISOString()}`);
// roughly equivalent to
// if (log != null) {
// log(`Request started at ${new Date().toISOString()}`);
// }
const result = (await fetch(url)).json();
log?.(`Request finished at at ${new Date().toISOString()}`);
return result;
}
 

Optional element access

Arrays are also objects , It's just not a special object , Access... Through a numeric index as an attribute . therefore Optional Chaining It can also be used to access array elements , This is where optional element access The function of , See the example from the official documentation :

/**
 * Get the first element of the array if we have an array.
 * Otherwise return undefined.
 */
function tryGetFirstElement<T>(arr?: T[]) {
return arr?.[0];
// equivalent to
// return (arr === null || arr === undefined) ?
// undefined :
// arr[0];
}
 

and && The difference between

although Optional Chaining Instead of following through && To realize the null operation :

// Before
if (foo && foo.bar && foo.bar.baz) {
// ...
}
 

but Optional Chaining and && There is still a difference , The latter uses JavaScript The short-circuit mechanism in , encounter False value Interrupt execution . And the former will only be judged when the object is null or undefined The execution will be interrupted when the system is running .

Please see the following example :

const a: any = 0;
console.log(a?.blah);
console.log(a && a.blah);
const b: any = false;
console.log(b?.blah);
console.log(b && b.blah);
const c: any = "";
console.log(c?.blah);
console.log(c && c.blah);
 

Output :

undefined
0
undefined
false
undefined
 

You can see , adopt Optional Chaining All the output of the control part undefined, Because the object to be determined here is not null or undefined, So the statement will be executed later , Try to visit blah, The value you get is undefined, The final output .

And by && A statement that makes a decision , Because the determined object is a false value , Interrupts execution and returns the current object .

Nullish Coalescing

Nullish Coalescing adopt ?? The operator , by null or undefined Provides the default value for .

such as :

let x = foo ?? bar();
 

The above expression is equivalent to if foo yes null or undefined, Call bar().

similarly , He replaced the one who passed || The default value effect of the operator , But the latter is also achieved by judging Boolean truth values , and Nullish Coalescing Only judge null or undefined.

such as :

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

Here if localStorage.volume Is set to 0, At last volume Get is 0.5, That is to say, it is set at localStorage.volume It will never work . and Nullish Coalescing We can avoid this kind of problem .

Related resources

The text was updated successfully, but these errors were encountered:

Please bring the original link to reprint ,thank
Similar articles