Horje
How to implement optional chaining in TypeScript?

The optional chaining in TypeScript is a process of searching and calling the variables, methods, properties, and parameters that might have nil existence in the code. It was introduced in the TypeScript 3.7 version. It is a way of accessing the properties and methods without even checking for the existence of them. Optional Chaining can help avoid the runtime errors that occur due to attempting to access the variables that contain null or undefined values.

Example: The below code will explain how you can implement the optional chaining in TypeScript.

Javascript

interface myInterface {
    company?: {
        name: string;
        desc: string;
    }
}
 
const myObj: myInterface = {
    company: {
        name: "GeeksforGeeks",
        desc: "A Computer Science Portal"
    }
}
 
const myObj2: myInterface = {}
console.log
    (myObj.company, myObj2.company)

Output:

{
name: "GeeksforGeeks",
desc: "A Computer Science Portal"
}
undefined



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
Explain the concept of enums in TypeScript ? Explain the concept of enums in TypeScript ?
How to handle asynchronous operation in TypeScript? How to handle asynchronous operation in TypeScript?
What is the never type in TypeScript? What is the never type in TypeScript?
How to use generics in TypeScript? How to use generics in TypeScript?
Explain the use of the readonly modifier in TypeScript ? Explain the use of the readonly modifier in TypeScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12