Home > front end >  Shortest way to call possibly undefined function
Shortest way to call possibly undefined function

Time:10-24

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?

CodePudding user response:

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

  • Related