TypeScript中??和?什么意思呢?

??其实没啥意思,就是Nullish Coalescing (空值合并)。

具体好好看官方文档:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
4.0的版本要有一些变化https://github.com/microsoft/TypeScript/issues/37255

来直接上代码简单例子一目了然

const i = undefined
const k = i ?? 5
console.log(k) // 5

// 3.9.2编译
const i = undefined;
const k = i !== null && i !== void 0 ? i : 5;
console.log(k); // 5

这个时候你肯定是想说了这样不就完了吗?

 let k = i || 5

虽然这样也用,但是你不觉得很不严谨吗? 如果i = 0呢对吧,看你排不排0. && 同理。

?存在不存在,可选,再有就是Optional Chaining的判断
具体好好看官方文档:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

来直接上代码简单例子一目了然

const o = {
    a: 1,
    b: {
        c: {
            d:2
        }
    }
}
if (o?.b?.c?.d) {
    console.log(1)
}
// 3.9.2编译
var _a, _b;
const o = {
    a: 1,
    b: {
        c: {
            d: 2
        }
    }
};
if ((_b = (_a = o === null || o === void 0 ? void 0 : o.b) === null || _a === void 0 ? void 0 : _a.c) === null || _b === void 0 ? void 0 : _b.d) {
    console.log(1);
}

?. 只能检查左侧,就是跟在谁后面检查谁。&&虽然也可以 但是并不严谨(0),这样就节省了很多吧, 减少层级判断了吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值