Câu hỏi phỏng vấn Typescript
Câu hỏi

What is Optional Chaining in TypeScript?

Câu trả lời

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.

How Optional Chaining Works

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.

Examples of Optional Chaining

  1. Property Access:

    typescript Copy
    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
  2. Method Calls:

    typescript Copy
    class User {
        getProfile() {
            return {
                getName: () => "John Doe"
            };
        }
    }
    
    const user = new User();
    const userName = user.getProfile()?.getName?.(); // "John Doe"

...

junior

junior

Gợi ý câu hỏi phỏng vấn

junior

What are assertion functions?

middle

What is Structural Typing?

entry

What is TypeScript and why do we need it?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào