2024年12月25日 建站教程
举例说明
function getval(x: number, y?: number) {
  return x + (y || 0);
}
getval(1, 2);
getval(1);
getval(1, undefined);
getval(1, null); // error, 'null' is not assignable to 'number | undefined'
?? 和 || 的意思有点相似,但是又有点区别。 ?? 表示当值为undefined或者null时,就会取后面的值; || 表示当前面的值为假值是 则去后面的值
console.log(null || 5) //5 console.log(null ?? 5) //5 console.log(undefined || 5) //5 console.log(undefined ?? 5) //5 console.log(0 || 5) //5 console.log(0 ?? 5) //0
?.的意思基本和 && 是一样的
a?.b 相当于 a && a.b ? a.b : undefined
const a = {
  b: { c: 7 }
};
console.log(a?.b?.c);     //7
console.log(a && a.b && a.b.c);    //7
			
                                        本文链接:http://so.lmcjl.com/news/20107/