Updated April 20, 2023
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.
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:
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:
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:
We have an error here,
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:
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.