Coming from a background in C# the null-conditional operator allows you to call a function avoiding a possible null-reference exception like so:
Func<int> someFunc = null;
int? someInteger = someFunc?.Invoke();
// someInteger == null
Given that Typescript has the "optional chaining operator" .? with very similar functionality I'm wondering if there's a way to do the same with a similarly concise piece of code. The best I can come up with is using a conditional expression:
let someFunc: (() => number) | undefined = undefined;
let someNumber = someFunc !== undefined ? someFunc() : undefined;
Perhaps apply and call can be utilized somehow?
Conditional invocation is possible in Typescript. Introduced in 3.7 as optional chaining.
const a = () => {console.log('hey')}
const b = null
a?.()
b?.()
The linter might complain but it complies and runs, see this playground
Read more about it in this blog or in the offical docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With