关于typescript:typescript的-和-和什么意思

?:是指可选参数,能够了解为参数主动加上undefined

function echo(x: number, y?: number) {
    return x + (y || 0);
}
getval(1); // 1
getval(1, null); // error, 'null' is not assignable to 'number | undefined'
interface IProListForm {
  enterpriseId: string | number;
  pageNum: number;
  pageSize: number;
  keyword?: string; // 可选属性
}

?? 和 || 的意思有点类似,然而又有点区别,??相较||比拟谨严, 当值等于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

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据