首页 > 其他 > 详细

typescript的?? 和?: 和?.什么意思

时间:2020-09-22 17:34:36      阅读:31      评论:0      收藏:0      [点我收藏+]

?:的意思指的是参数自动加上undefined

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‘

?? 和 || 的意思有点相似,但是又有点区别,??相较||比较严谨, 当值等于0的时候||就把他给排除了,但是?? 不会

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

 

typescript的?? 和?: 和?.什么意思

原文:https://www.cnblogs.com/yhhBKY/p/13712452.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!