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#.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay