Attempt #19 - Compile-Time Safety with `never` in TypeScript: A Quick Comparison with C#
dilsemonk
Posted on September 2, 2024
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();
}
}
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
}
}
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#.
💖 💪 🙅 🚩
dilsemonk
Posted on September 2, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.