来自c#背景的空条件运算符允许您调用函数以避免可能的空引用异常,如下所示:
Func<int> someFunc = null;
int? someInteger = someFunc?.Invoke();
// someInteger == null
假定Typescript有"可选的链接操作符".?
具有非常相似的功能,我想知道是否有一种方法可以用同样简洁的代码来做同样的事情。我能想到的最好的方法是使用条件表达式:
let someFunc: (() => number) | undefined = undefined;
let someNumber = someFunc !== undefined ? someFunc() : undefined;
也许apply和call可以被利用?
条件调用在Typescript中是可能的。在3.7中引入可选链接.
const a = () => {console.log('hey')}
const b = null
a?.()
b?.()
linter可能会抱怨,但它服从并运行,看看这个playground
在这个博客或官方文档中阅读更多关于它的信息