How can we use optional chaining in TypeScript?
How can we use 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 check each level for null or undefined. This feature simplifies the code and makes it more readable by reducing the need for repetitive and cumbersome null checks.
The syntax for optional chaining is ?.. It can be used in several contexts:
const obj = { prop1: { prop2: { prop3: 'value' } } };
const value = obj?.prop1?.prop2?.prop3; // 'value'
const arr = [1, 2, 3];
const value = arr?.[0]; // 1
const obj = {
myFunc: () => console.log('Function exists'),
};
obj.myFunc?.(); // Calls myFunc if it exists
When dealing with variables of type unknown, TypeScript disables type inference, requiring the type to be cast before using optional chaining. This is because unknown can be any type, including non-objects, and attempting to use optional chaining directly on an unknown type will result in an error.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.