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

How can we use 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 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.

Basic Usage

The syntax for optional chaining is ?.. It can be used in several contexts:

  1. Property Access: When accessing a property of an object that might be null or undefined.
typescript Copy
const obj = { prop1: { prop2: { prop3: 'value' } } };
const value = obj?.prop1?.prop2?.prop3; // 'value'
  1. Array Access: When accessing an array index that might not exist.
typescript Copy
const arr = [1, 2, 3];
const value = arr?.[0]; // 1
  1. Function or Method Calls: When invoking a function or method that might not be defined.
typescript Copy
const obj = {
  myFunc: () => console.log('Function exists'),
};
obj.myFunc?.(); // Calls myFunc if it exists

Handling Unknown Types

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[1].

Practical Examples

  • Accessing Nested Properties: Optional chaining shines when you need to access deeply nested properties within an object. It eliminates the need for multiple null checks[2][3].

  • Safe Function Calls: It allows for safe calling of functions that may not exist, especially useful when dealing with objects that have optional methods[3][7].

  • Working with Arrays: Optional chaining can be used to safely access array elements without worrying about out-of-bounds errors[14].

  • Combining with Nullish Coalescing: Optional chaining pairs well with the nullish coalescing operator (??) to provide default values when accessing nullable properties or calling functions that might return null or undefined[6][7].

Limitations and Considerations

  • **T...
junior

junior

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

senior

What is Mixin Constructor Type?

middle

What is the default access modifier for members of a class in TypeScript?

middle

What is Structural Typing?

Bình luận

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

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