EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Optional Chaining
 

TypeScript Optional Chaining

Priya Pedamkar
Article byPriya Pedamkar

Updated April 20, 2023

TypeScript Optional Chaining

 

 

Introduction to TypeScript Optional Chaining

TypeScript optional chaining is a process of querying and calling properties, subscripts, and methods on optional that might be nil. ECMAScript feature allows developers to stop running if expressions encounter undefined or null values. TypeScript, being a superset of JavaScript offers IDE support and minimal configuration, with the provision of benefit from JavaScript libraries. The latest release of TypeScript has two addons, which include Optional chaining and nullish coalescing operators. As a core part of TypeScript, optional chaining involves in writing code where the script stops running if a user runs into undefined or null. Operator ?. is used for optional property access. Let us look into how Optional chaining works, its syntax, and how it is implemented.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax:

Here is the syntax for optional chaining in TypeScript

Before looking into a new operator, we shall see how code looked like before replacing it with ?.

let sample_x = (value1 === null || value1 === undefined) ? undefined : value1.function();
if( value1 && value1.function && value1.function.value2) {
-----------------
-----------------
}
With optional chaining, a new operator ?. is replaced as below
let sample_x = value1?.function();
if (value1?.function?.value2) {
-------------------
-------------------
}

This new operator ?. is different from && checks as optional chaining treats valid data as 0 or as empty as truthy.

How Optional Chaining operator works in TypeScript?

Let us see how the Optional Chaining operator works in TypeScript.

  • Optional chaining uses ?. operator to access optional properties of a value.
  • New ?. operator allows the user to have an inline check if the property accessed does exist or not.
  • Optional chaining has two other operations included:
    • Optional element access, for accessing non-identifier properties such as strings and numbers
    • Optional call, for calling expressions conditionally if they are not undefined or null
  • The above syntax says when value1 is undefined, value1.function.value2 will be computed but if value1 is null or undefined, computation stops and returns null or undefined.
  • If a function() is null or undefined, the code will hit an error in accessing value2. Similarly, if value2 computes to null or undefined, will hit an error.
  • This means the optional chaining operator ( ?. ) checks only whether the value on the left of any is null or undefined.
  • Simply optional chaining operator replaces the repetitive nullish checks using && operator,
Like, if( value1 && value1.function && value1.function.value2 ) {
ß----------à
}
After ?. operator,
if (value1?.function?.value2) {
ß--------à
}
  • ?. operator acts differently from those && operators since && operators act on ‘falsy’ values i.e. empty string, NaN, 0, and also false

Example #1: Simple example of Optional chaining operator

let value1 = {
function: 'optional chaining',
}
console.log('Value of function:', value1?.function);

Output:

typescript 1

So here we are passing a value ‘optional chaining’ to the argument function. To print the value or to access the function value, we need to use a dot(.) operator and && operator. With the new operator ?. will allow us to check the value is null or undefined else print the data.

Example #2: Optional chaining to check for null or undefined value. (let us take the previous example to understand better)

let value1 = {
function: 'optional chaining',
function1: 'operator'
}
console.log('Value of function:', value1?.function2);

Output:

typescript optional chaining 2

Here, we are passing one more value ‘function1’, but there is no ‘function2’; hence the value would be undefined or null. Operator when checks for value1 if present checks for function2, which is not present as a parameter in value1, hence returns undefined.

Example #3: Optional chaining for response from API

const response = {
data: {
id: 101,
name: 'karthik',
age: 24,
desg: 'SSE',
}
}
console.log("person details", response?.data?.id, response?.data?.name, response?.data?.age, response?.data?.desg);
console.log("metadata using optional chaining", response?.metadata?.requestId)
console.log("metadata", response.metadata.requestId)

Output:

typescript optional chaining 3

We have an error here,

typescript optional chaining 4

It is the TypeError, as there is no metadata in the response. Also the last line, we are not using the ?. operator and only dot(.) operator to print the value which is not possible.

Optional chaining works whenever there is a need to ensure that there is a presence of function or property before accessing and prevent an error if the property or function does not exist.

Example #4: undefined values with optional chaining

let employee = null;
console.log( employee?.id );
console.log( employee?.address.colony );

Output:

example 4

Here the employee variable is totally null, and there are no attributes. Hence, any value would be undefined

Optional chaining operator should not be overused, it should be used only where it is a necessity to know if the parameter exists or not. For example, let us consider the above code.

Based on the logic, the employee should have an object, which is a must, but having an id and address are optional. So the ?. operator can be used as,

employee.address?.colony instead of us employee?.address?.colony

If there is no employee object defined, it would lead to ReferenceError. It is a must that a variable has to be defined using let/ var/ const keywords. Or a function parameter can also be used for optional chaining.

Conclusion

With this, we shall conclude the topic ‘TypeScript Optional chaining’. We have seen what Optional chaining in TypeScript is and how it is implemented. It uses an operator ( ?. ) to check for values if present or not. Syntactically, it replaces lines of code used to check existence of the parameters. We have also seen few examples which are easy to understand and also show what errors user might face during Optional chaining. Also, ?. operator can be applicable to function parameters.

Recommended Articles

We hope that this EDUCBA information on “TypeScript Optional Chaining” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. TypeScript Array of Objects
  2. TypeScript keyof Enum
  3. TypeScript Set
  4. Typescript for loop

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW