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

How the never data...

Câu trả lời

The never type in TypeScript is a powerful and specialized type that can be extremely useful in several scenarios to enhance type safety and code maintainability. Here are some of the key uses and benefits of the never type:

1. Function Return Types for Non-returning Functions

The never type is used as the return type of functions that do not return a value to the caller because they cannot complete normally. These include functions that throw an error or enter an infinite loop. By specifying never as the return type, TypeScript can enforce that these functions do not have a reachable endpoint, thus preventing accidental returns.

  • Throwing Errors: Functions that throw exceptions should have a return type of never because the function execution terminates by throwing an error, and control is passed to the catch block or error handler, not back to the caller[1][2][3][4][5][6][7][8][10][13][14].

    typescript Copy
    function throwError(message: string): never {
      throw new Error(message);
    }
  • Infinite Loops: Functions with infinite loops are another example where the return type is never, as they never complete execution to return a value[7][13][14].

    typescript Copy
    function infiniteLoop(): never {
      while(true) {
        // Loop indefinitely
      }
    }

2. Enforcing Exhaustiveness in Switch Cases

The never type is useful in switch-case statements to ensure that all possible cases are handled. If a case is missed in a switch that handles a union of types, TypeScript can flag an error if the default case uses a function that expects a never type. This pattern is particularly useful when dealing with union types where each case might correspond to a different type[2][11].

typescript Copy
type Shape = "circle" | "square" | "triangle";

function getArea(shape: Shape): number {
  switch (shape) {
    case "circle": return Math.PI * 2 * 2;
    case "square": return 4 * 4;
    default: return assertNever(shape); // TypeScript will error if 'triangle' is not handled
  }
}

function assertNever(x: never): never {
  throw new Error("Unexpected object: " + x);
}

3. Preventing Certain Operations

Since never can be assig...

expert

expert

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

entry

What is TypeScript and why do we need it?

middle

What is the fundamental difference between Optional Chaining ( ?. ) and Non-null assertion operator ( ! )
in TypeScript?

junior

Describe what are conditional types in TypeScript?

Bình luận

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

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