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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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