'never' Type in TypeScript

  • In TypeScript, the `never` type represents a type that indicates something that will never occur. It is typically used to represent functions that will always throw an error, or cases that should never be reached within a program. The `never` type is a subtype of every other type in TypeScript, which means it can be assigned to any other type, but no other type can be assigned to `never`.
  • Here's an example to illustrate the usage of `never` type:


    function throwError(message: string): never {
        throw new Error(message);
    }

  • In this example, we have a function called `throwError` that takes a `message` parameter of type `string` and returns `never`. The function body throws an `Error` with the provided message. Since the `throw` statement never returns normally, the return type of the function is `never`.
  • Another common use case for `never` is when using exhaustive type checking with discriminated unions. Consider the following example:


    type Shape = Square | Circle;

    interface Square {
        kind: "square";
        size: number;
    }

    interface Circle {
        kind: "circle";
        radius: number;
    }

    function area(shape: Shape): number {
        switch (shape.kind) {
            case "square":
                return shape.size * shape.size;
            case "circle":
                return Math.PI * shape.radius * shape.radius;
            default:
                const exhaustiveCheck: never = shape;
                throw new Error(`Unhandled shape: ${exhaustiveCheck}`);
        }
    }

  • In this example, we define a `Shape` type that represents either a `Square` or a `Circle`. The `Shape` type has a discriminated union property called `kind` that allows us to distinguish between the different shapes. The `area` function calculates the area of the given shape.
  • The `default` case in the `switch` statement is unreachable because all possible values of `Shape` are already covered by the `case` statements. By assigning `shape` (of type `Shape`) to a variable of type `never` (`exhaustiveCheck`), we ensure that if the `default` case is ever reached, it will throw an error indicating that an unhandled shape was encountered.
  • To summarize, the `never` type in TypeScript is used to indicate that something will never occur. It is useful for functions that always throw errors or as a way to enforce exhaustive type checking in discriminated unions.

No comments:

Post a Comment