What is assert-never?
The assert-never package is a TypeScript utility that helps ensure exhaustive checks in switch statements and other control flow structures. It is particularly useful for handling TypeScript's union types and ensuring that all possible cases are handled, providing a compile-time error if a case is missed.
What are assert-never's main functionalities?
Exhaustive Check in Switch Statements
This feature ensures that all possible cases of a union type are handled in a switch statement. If a new type is added to the union and not handled in the switch, TypeScript will throw a compile-time error.
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
type Shape = 'circle' | 'square' | 'triangle';
function getArea(shape: Shape): number {
switch (shape) {
case 'circle':
return Math.PI * 1 * 1; // Example area calculation
case 'square':
return 1 * 1; // Example area calculation
case 'triangle':
return 0.5 * 1 * 1; // Example area calculation
default:
return assertNever(shape);
}
}
Exhaustive Check in If-Else Statements
This feature ensures that all possible cases of a union type are handled in an if-else statement. If a new type is added to the union and not handled in the if-else, TypeScript will throw a compile-time error.
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
type Color = 'red' | 'green' | 'blue';
function getColorCode(color: Color): string {
if (color === 'red') {
return '#FF0000';
} else if (color === 'green') {
return '#00FF00';
} else if (color === 'blue') {
return '#0000FF';
} else {
return assertNever(color);
}
}
Other packages similar to assert-never
typescript-is
The typescript-is package provides runtime type checking for TypeScript. It allows you to validate that a value conforms to a specific type at runtime, which can be useful for ensuring type safety in dynamic scenarios. Unlike assert-never, which focuses on compile-time exhaustive checks, typescript-is provides runtime validation.
ts-exhaustive-check
The ts-exhaustive-check package is another utility for ensuring exhaustive checks in TypeScript. It provides a similar functionality to assert-never by ensuring that all cases in a union type are handled. The main difference is in the API and usage patterns, but both aim to achieve the same goal of exhaustive type checking.
Assert Never
Helper function for exhaustive checks of discriminated
unions in TypeScript.
Installation
npm install --save assert-never
Usage
import {assertNever} from "assert-never";
type A = {type: 'a'};
type B = {type: 'b'};
type Union = A | B;
function doSomething(arg: Union) {
if (arg.type === 'a') {
return something;
}
if (arg.type === 'b') {
return somethingElse;
}
return assertNever(arg);
}