链判断运算符是一种先检查属性是否存在,再尝试访问该属性的运算符,其符号为 ?.
如果运算符左侧的操作数 ?. 计算为 undefined 或 null,则表达式求值为 undefined 。否则,正常触发目标属性访问,方法或函数调用。
我们来看一下官方提供的一些场景
a?.b; // undefined if `a` is null/undefined, `a.b` otherwise.
a == null ? undefined : a.b;
a?.[x]; // undefined if `a` is null/undefined, `a[x]` otherwise.
a == null ? undefined : a[x];
a?.b(); // undefined if `a` is null/undefined
a == null ? undefined : a.b(); // throws a TypeError if `a.b` is not a function
// otherwise, evaluates to `a.b()`
a?.(); // undefined if `a` is null/undefined
a == null ? undefined : a(); // throws a TypeError if `a` is neither null/undefined, nor a function
// invokes the function `a` otherwise
截至目前(2018 年 12 月) 链判断运算符 还处于 stage1 阶段,TS 也暂时不支持,TS 社区也正在等待 TC39 指出链判断运算符的最终方向。