Optional Chaining with Array
In this approach, we are using optional chaining with array elements, where we are accessing the first author in the authors array of the geeksArticle object. We are storing the result in mainAuth, which prints the author name or ‘undefined‘ if the authors array is not defined or empty.
Syntax:
const result = object?.property?.[index]?.method();
Example: Below is the implementation of the above-discussed approach.
interface Approach1 {
title: string;
authors?: string[];
}
const geeksArticle: Approach1 = {
title: 'Top 10 TypeScript Features',
authors: ['Geek1', 'Geek2', 'Geek3'],
};
const mainAuth: string | undefined =
geeksArticle.authors?.[0];
console.log(mainAuth);
Output:
"Geek1"
How to use Optional Chaining with Arrays and Functions in TypeScript ?
In this article, we will learn how we can use optional chaining with arrays and functions in TypeScript. Optional chaining in Typescript is mainly a feature that allows us to safely access the properties or the call functions on potentially null or undefined values without causing any runtime errors. We will see three different approaches with implementation in terms of examples.
Below are the possible approaches:
Table of Content
- Optional Chaining with Array
- Optional Chaining with Functions
- Optional Chaining with Array and Functions
Contact Us