DEV Community

dilsemonk
dilsemonk

Posted on

Attempt #19 - Compile-Time Safety with `never` in TypeScript: A Quick Comparison with C#

TypeScript offers a powerful feature that languages like C# often miss: compile-time safety. The never type in TypeScript plays a crucial role in ensuring that all possible cases in a union type are handled, catching errors early—before your code even runs.

C# Example

In C#, if you have an enum and a switch statement, unhandled cases are caught at runtime:

public enum ShapeType { Circle, Square, Rectangle }

public double GetArea(ShapeType shape)
{
    switch (shape)
    {
        case ShapeType.Circle: // ...
        case ShapeType.Square: // ...
        case ShapeType.Rectangle: // ...
        default:
            throw new ArgumentOutOfRangeException();
    }
}
Enter fullscreen mode Exit fullscreen mode

TypeScript’s never Example

TypeScript enforces exhaustiveness at compile-time, using the never type:

type Shape = { kind: "circle" } | { kind: "square" } | { kind: "rectangle" };

function getArea(shape: Shape): number {
    switch (shape.kind) {
        case "circle": // ...
        case "square": // ...
        case "rectangle": // ...
        default:
            const _exhaustiveCheck: never = shape;
            return _exhaustiveCheck; // Compile-time error if a case is missed
    }
}
Enter fullscreen mode Exit fullscreen mode

By catching unhandled cases during compilation, TypeScript’s never type helps you write more robust and error-free code, reducing the chances of runtime surprises common in C#.

Top comments (0)