TypeScript Optional Chaining
Optional chaining is a safe way to access properties in TypeScript and JavaScript.
It allows developers to safely access nested object properties in a chained manner. When any property in the access path is null or undefined, the entire expression short-circuits and returns undefined instead of throwing an error.
This greatly simplifies the property access code for deeply nested objects.
Why optional chaining is needed
In JavaScript/TypeScript development, it is often necessary to access deeply nested object properties.
The traditional approach requires checking layer by layer whether a property exists. This approach is not only verbose, but also prone to missed checks that cause runtime errors.
Concept explanation:The core of optional chaining is "short-circuit evaluation". When the value of a property in the chain is null or undefined, the result of the entire expression immediately returns undefined without continuing to access subsequent properties.
Basic Syntax
Use ?. The operator safely accesses properties that may not exist.
Compared with traditional && chain checks, optional chaining syntax is more concise and intuitive.
Example
// Define a nested user object
// Contains name and address information, with a city in the address
var
user
=
{
name
:
"RUNOOB"
,
address
:
{
city
:
"Beijing"
}
}
;
// Traditional approach: use && to check layer by layer
// This approach is verbose and easy to miss checks
var
city1
=
user
&&
user.
address
&&
user.
address
.
city
;
// Optional chaining approach: use the ?. operator
// If any layer is null or undefined, return undefined directly
var
city2
=
user
?
.
address
?
.
city
;
console.
log
(
"Traditional approach: "
city1
)
;
console.
log
(
"Optional chaining: "
city2
)
;
Running result:
传统方式: Beijing
可选链: Beijing
Tip:When the object property exists, both approaches produce the same result. But optional chaining code is more concise and easier to read.
Handling non-existent properties
When a property in the access path does not exist, optional chaining safely returns undefined instead of throwing an error.
This is particularly useful for handling data from APIs or user form input.
Example
// Define an incomplete user object
// Only has the name property, no address property
var
user
=
{
name
:
"RUNOOB"
// The address property does not exist
}
;
// Use optional chaining to access deep properties
// user.address is undefined, so city is also undefined
var
city
=
user
?
.
address
?
.
city
;
// Access even deeper nested properties
// Even if country does not exist, undefined is still returned without an error
var
country
=
user
?
.
address
?
.
country
?
.
name
;
console.
log
(
"City: "
city
)
;
console.
log
(
"Country: "
country
)
;
Running result:
城市: undefined
国家: undefined
Note:Optional chaining only returns undefined when accessing a property; it does not create new objects or properties.
Combining optional chaining with arrays
Optional chaining can be combined with array index access to safely access elements in an array.
Use ?.[index] This syntax can return undefined when an array element does not exist.
Example
// Define an array of users
var
users
=
[
{
name
:
"Alice"
}
,
{
name
:
"Bob"
}
]
;
// Safely access the name of the first element in the array
// users?.[0] exists, returns "Alice"
var
firstUser
=
users
?
.
[
0
]
?
.
name
;
// Safely access an element that does not exist in the array
// users?.[9] does not exist (the array has only 2 elements), returns undefined
var
tenthUser
=
users
?
.
[
9
]
?
.
name
;
console.
log
(
"First user: "
firstUser
)
;
console.
log
(
"Tenth user: "
tenthUser
)
;
Running result:
第一个用户: Alice
第十个用户: undefined
Explanation:
?.[index]The difference between?.The difference between them is: the former is used for arrays, the latter for object properties.
Optional chaining with method calls
Optional chaining can be used to safely call methods that may not exist.
Use ?.() This syntax returns undefined if the method does not exist, without throwing an error.
Example
// Define a user object with a name and a greet method
var
user
=
{
name
:
"Alice"
,
// Define a greeting method
greet
:
function
(
)
{
return
"Hello, "
this
.
name
;
}
}
;
// Safely call a method that exists
// user.greet exists, called normally and returns the result
var
message1
=
user.
greet
?
.
(
)
;
// Safely call a method that does not exist
// user.sayHello does not exist, returns undefined without an error
var
message2
=
user.
sayHello
?
.
(
)
;
console.
log
(
"greet: "
message1
)
;
console.
log
(
"sayHello: "
message2
)
;
Running result:
greet: Hello, Alice
sayHello: undefined
Application scenarios:This is particularly useful when dealing with optional callback functions or event handlers.
Optional chaining assignment
Optional chaining can also be used in assignment operations, but its behavior needs attention.
Optional chaining assignment only modifies paths that already exist and does not automatically create intermediate objects.
Example
// Define a simple user object
var
user
=
{
name
:
"Alice"
}
;
// Try using optional chaining assignment
// user?.address does not exist, so the entire assignment is skipped
// The user object remains unchanged
user
?
.
address
?
.
city
=
"Beijing"
;
console.
log
(
"User: "
JSON.
stringify
(
user
)
)
;
Running result:
用户: {"name":"Alice"}
Note:Optional chaining assignment cannot be used to create new properties. If you need to create nested objects, you should use the traditional approach to create the intermediate objects first.
Nullish coalescing and optional chaining
Optional chaining is often used together with the nullish coalescing operator ?? in combination.
This combination can provide a default value when a property does not exist, making the code more robust.
Example
// Define an incomplete user object
var
user
=
{
name
:
"Alice"
// address does not exist
}
;
// Optional chaining + nullish coalescing: use the default value when city is null or undefined
var
city
=
user
?
.
address
?
.
city
??
"Unknown city"
;
console.
log
(
"City: "
city
)
;
// Comparison: the complex traditional approach
var
country
=
user
&&
user.
address
&&
user.
address
.
country
?
user.
address
.
country
:
"Unknown country"
;
console.
log
(
"Country: "
country
)
;
Running result:
城市: 未知城市
国家: 未知国家
Explanation:
??uses the default value only when the value is null or undefined, while||also uses the default value when the value is falsy (0, "", false). When handling numbers or strings, you should prefer??。
Notes
- **Short-circuit evaluation:** Optional chaining returns immediately when it encounters null or undefined, without continuing to access subsequent properties
- **Cannot create properties:** Optional chaining assignment does not automatically create intermediate objects
- **Combined with nullish coalescing:** It is recommended to always use
??to provide default values, and use less|| - **Performance consideration:** Although optional chaining is safer, direct access performs better when a property is guaranteed to exist
Note:In actual development, for properties from external data (such as API responses and user input), prefer optional chaining for safe access.
Summary
Optional chaining is an important feature in modern JavaScript/TypeScript for handling nested objects.
- **
?.:**Safely access object properties - **
?.[index]:**Safely access array elements - **
?.():**Safely call methods that may not exist - **
??:**Provide default values and handle undefined cases
Best practices:Always use optional chaining for deep property access that may not exist. Combined with the nullish coalescing operator, you can write code that is both safe and concise.