??其实没啥意思,就是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),这样就节省了很多吧, 减少层级判断了吧。