乐闻世界logo
搜索文章和话题

What is never type and its uses in TypeScript?

1个答案

1

In TypeScript, the never type represents the type of values that can never occur. Specifically, it is the return type of function expressions or arrow functions that always throw exceptions or never return a value. This means that when a function throws an error or enters an infinite loop, its return type is never.

The Uses of the never Type

  1. Enhancing Program Type Safety: Using the never type helps prevent unexpected behavior in certain scenarios. For example, by ensuring that functions do not inadvertently return a value, we can avoid introducing potential errors in functions that require strict control over return values.

  2. For Unreachable Code Scenarios: In functions, if there are code segments that are logically unreachable, TypeScript marks them with the never type. This helps developers identify errors or unnecessary code during the coding process.

  3. In Exhaustive Checks: In scenarios involving union types and type guards, the never type can be used to ensure that all possible cases are handled. If there are unhandled cases, the program will report an error.

Examples

Example 1: Using the never Type to Mark Functions That Do Not Return

typescript
function throwError(errorMsg: string): never { throw new Error(errorMsg); } function keepProcessing(): never { while (true) { console.log('I will never stop!'); } }

Example 2: Using never in Exhaustive Checks

typescript
type Shapes = "circle" | "square" | "triangle"; function getArea(shape: Shapes): number { switch (shape) { case "circle": // Calculate the area of a circle return Math.PI * Math.pow(10, 2); case "square": // Calculate the area of a square return 10 * 10; case "triangle": // Calculate the area of a triangle return 0.5 * 10 * 10; default: const _exhaustiveCheck: never = shape; return _exhaustiveCheck; } }
2024年7月29日 13:29 回复

你的答案