Tiny runtime assertion with TypeScript narrowing
npm install @philiprehberger/invariant-tsTiny runtime assertion with TypeScript narrowing
npm install @philiprehberger/ts-invariant
import { invariant, assertNever, unreachable } from '@philiprehberger/ts-invariant';
const user = getUser(id);
invariant(user, 'User %s not found', id);
user.name; // narrowed to User
// Lazy message
invariant(data, () => `Expected data, got ${typeof data}`);
// Exhaustiveness checking
type Shape = 'circle' | 'square';
switch (shape) {
case 'circle': return handleCircle();
case 'square': return handleSquare();
default: assertNever(shape);
}
import { assertDefined, assertType } from '@philiprehberger/invariant-ts';
function findUser(id: string): User | undefined { /* ... */ }
const user: User | undefined = findUser(id);
assertDefined(user, 'User must exist');
user.name; // narrowed to User
const isUser = (v: unknown): v is User =>
!!v && typeof v === 'object' && 'id' in v;
assertType(payload, isUser, 'Invalid user payload');
payload.name; // narrowed to User
import { invariantAs } from '@philiprehberger/ts-invariant';
class NotFoundError extends Error {
constructor(message?: string) {
super(message);
this.name = 'NotFoundError';
}
}
invariantAs(NotFoundError, user, 'User not found');
| Function | Description |
|---|---|
invariant(condition, message?, ...args) | Assert condition is truthy, narrows type |
invariantAs(ErrorClass, condition, message?) | Assert with custom error type |
assertDefined(value, message?) | Narrow T | null | undefined to T |
assertType(value, guard, message?) | Narrow via a custom type guard |
assertNever(value) | Exhaustiveness checking for switch/if chains |
unreachable(message?) | Mark unreachable code paths |
InvariantError | Error class thrown by invariant() |
npm install
npm run build
npm test
If you find this project useful: