Open In App

How to implement optional chaining in TypeScript?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads