Working with Optional Chaining in TypeScript

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with Optional Chaining in TypeScript

Optional chaining is a powerful feature of TypeScript which allows developers to navigate through deeply nested properties of an object, without the risk of getting a runtime exception. Instead of having to check for the existence of each object property before accessing it, optional chaining lets you write shorter and simpler code.

The optional chaining syntax uses the question mark (?) character. The ?. operator is used to access a nested property within an object. If the initial property exists, then the second property is accessed and its value is returned. If the property doesn’t exist then the ?. operator returns undefined. Here’s an example of optional chaining used to access a property of an object.

let employee = {
  name: 'John Doe',
  department: {
    id: 123,
    manager: 'Jane Doe'
  }
}

let managerName = employee?.department?.manager
// managerName will be 'Jane Doe'

In this example we can see that if either the 'department' property or the 'manager' property does not exist, then the ?. operator will return undefined instead of throwing an error. This eliminates the need to check for the existence of each property before accessing it.

Another useful feature of optional chaining is the ability to call methods from an object. Using the same example as above, the following code shows how to call a method on an object using optional chaining.

let employee = {
  name: 'John Doe',
  department: {
    id: 123,
    manager: 'Jane Doe', 
    getEmployeeInfo() {
      return `${this.name}: ${this.manager}`
    }
  }
}

let employeeInfo = employee?.department?.getEmployeeInfo()
// employeeInfo will be 'John Doe: Jane Doe'

Optional chaining can be used with other operators too. For example, the spread operator can be used to get all of the values from an object.

let employee = {
  name: 'John Doe',
  department: {
    id: 123,
    manager: 'Jane Doe', 
    employees: ['Bob', 'Tom']
  }
}

let employees = [...employee?.department?.employees]
// employees will be ['Bob', 'Tom']

As you can see, optional chaining is a powerful feature of TypeScript which allows developers to write simpler and more concise code. Keep in mind that optional chaining works only with properties, not variables, so you cannot use it to call functions or methods.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.