What is Optional Chaining in TypeScript?
What is Optional Chaining in TypeScript?
Optional Chaining in TypeScript is a powerful feature that allows developers to safely access deeply nested properties, methods, and arrays within objects without having to explicitly check if each reference in the chain is null or undefined. This feature is particularly useful in scenarios where there is uncertainty about the presence of certain properties or methods in an object structure, potentially due to variations in data sources or incomplete data.
The syntax for Optional Chaining in TypeScript utilizes the ?.
operator. This operator acts as a safe navigation operator that only attempts to access the property or method if the preceding part of the chain is not null or undefined. If at any point a null or undefined is encountered, the expression short-circuits and returns undefined immediately, thus preventing runtime errors that would normally arise from trying to access properties of null or undefined.
Property Access:
const user = {
profile: {
name: "John Doe",
details: {
age: 30,
address: null
}
}
};
// Accessing nested property safely
const userAge = user.profile?.details?.age; // 30
const userAddress = user.profile?.details?.address; // null
const userPhone = user.profile?.details?.phone; // undefined
Method Calls:
class User {
getProfile() {
return {
getName: () => "John Doe"
};
}
}
const user = new User();
const userName = user.getProfile()?.getName?.(); // "John Doe"
...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào