How to use optional chaining with array or functions with TypeScript?

Sometimes, we want to use optional chaining with array or functions with TypeScript.

In this article, we’ll look at how to use optional chaining with array or functions with TypeScript.

How to use optional chaining with array or functions with TypeScript?

To use optional chaining with array or functions with TypeScript, we can use the ?. operator.

For instance, we write

myArray.filter((x) => x.testKey === myTestKey)?.[0];

to return the first entry of the array returned by myArray.filter.

We can use the optional chaining operator to call functions by writing

obj.fn1?.();

Conclusion

To use optional chaining with array or functions with TypeScript, we can use the ?. operator.