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

How could you check null and undefined in TypeScript?

Câu trả lời

In TypeScript, checking for null and undefined values is a common task, as these values often represent the absence of a value or uninitialized variables. There are several methods to check for these values effectively:

Using Equality Check (== and ===)

  • Loose Equality (==): Using == checks for both null and undefined simultaneously. This is because null and undefined are loosely equal to each other.

    typescript Copy
    if (value == null) {
      // This will be true if value is null or undefined
    }
  • Strict Equality (===): Using === provides a strict check against either null or undefined, meaning it checks both the value and the type.

    typescript Copy
    if (value === null) {
      // This will be true only if value is exactly null
    }
    if (value === undefined) {
      // This will be true only if value is exactly undefined
    }

Using Type Guards

  • typeof: You can use the typeof operator to check specifically for undefined.

    typescript Copy
    if (typeof value === 'undefined') {
      // This will be true only if value is undefined
    }
  • Type Guard Functions: Custom type guard functions can be defined to check for null or undefined.

    typescript Copy
    function isNullOrUndefined(value: any): value is null | undefined {
      return value === null || typeof value === 'undefined';
    }

Using the Nullish Coalescing Operator (??)

Introduced in TypeScript 3.7, the nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

typescript Copy
const result = value ?? "default value";
// If value is null or undefined, result will be "default value"

Using Optional Chaining (?.)

Optional chaining (?.) allows you to safely access deeply nested properties of an object without having to explicitly check if each reference in the chain is nullish (null or undefined).

typescript Copy
const nestedValue = obj?.prop?.nestedProp;...
junior

junior

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

junior

What is the purpose of Nullish Coalescing operator?

senior

What is Mixin Constructor Type?

middle

What is Mixin Class in TypeScript?

Bình luận

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

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