Categories
TypeScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *