Open In App

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.




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
Article Tags :