How optional chaining works in TypeScript?


In this article, you will understand how optional chaining works in TypeScript. Optional chaining operator (?.) accesses an object’s property. If the objects property is null or not defined, it returns ‘undefined’. Let us first understand what TypeScript is.

Strongly typed programming language TypeScript, which is based on JavaScript, gives you better tools at any scale. Code written in TypeScript can be converted to execute in any JavaScript-compatible environment. JavaScript is understood by TypeScript, and type inference is used to provide excellent tooling without the need for additional code.

Example 1

In this example, we use the optional chaining operator and call the function twice. The first call returns the objects property and the second call returns ‘undefined’ −

let displayMessage = (firstWord , lastWord) => {
   return "Message : " + firstWord + " " + lastWord;
}
console.log("The first input words are Good and Evening")
console.log("The Display message is: ")
console.log(displayMessage("Good", "Evening"));

console.log("
The first input words are Good") console.log("The Display message is: ") console.log(displayMessage("Good"));

Output

The first input words are Good and Evening
The Display message is: 
Message : Good Evening
The first input words are Good and Morning
The Display message is: 
Message : Good undefined

Explanation

  • Step 1 −Define a function ‘displayMessage’ that takes in two strings and prints them together.

  • Step 2 −Call the function with two strings and print the result.

  • Step 3 −Call the function with just one string and display the result.

Example 2

type User = {
   id: number;
   name?: {
      firstWord: string;
      lastWord?: string;
   }
};
const users: User[] = [{
   id: 1,
   name: {
      firstWord: "Welcome"
   }
},
{
   id: 2,
   name: {
      firstWord: "Good",
      lastWord: "Evening"
   }
},
{
   id: 3
},
];
console.log("The first input word is Welcome")
console.log("The second input words are Good and Evening")

console.log("After calling the values, the result is")
users.map(element => console.log(element.name?.lastWord));
users.map(element => console.log(element.name?.lastWord));

Output

The first input word is Welcome
The second input words are Good and Evening

After calling the values, the result is

undefined 
"Evening" 
undefined 

Explanation

  • Step 1 −Define multiple variables that take in different values such as strings or numbers as parameters and in different quantities.

  • Step 2 −Call the variables. If the parameter type and value matches, the variables are displayed. If the parameters don't match, ‘undefined’ is returned.

Updated on: 16-Feb-2023

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements