[TypeScript ] Using the Null Coalescing operator with TypeScript 3.7

The postshows you how to use the null coalescing operator (??) instead of logical or (||) to set default values in TypeScript 3.7 to prevent expected bugs in your code.

  
const val = 0;
const correct = (val !== undefined && val !== null) ? val : 0.5;
// const incorrect = val || 0.5; // || check all the falsy value
const incorrect = val ?? 0.5; // ?? check only null and undefined
console.log({ correct, incorrect });

 

posted @ 2019-10-10 15:25  Zhentiw  阅读(207)  评论(0)    收藏  举报