@philiprehberger/invariant-ts
v0.2.0
Published
Tiny runtime assertion with TypeScript narrowing
Downloads
48
Readme
@philiprehberger/ts-invariant
Tiny runtime assertion with TypeScript narrowing
Installation
npm install @philiprehberger/ts-invariantUsage
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);
}Defined / Typed Assertions
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 UserCustom Error Classes
import { invariantAs } from '@philiprehberger/ts-invariant';
class NotFoundError extends Error {
constructor(message?: string) {
super(message);
this.name = 'NotFoundError';
}
}
invariantAs(NotFoundError, user, 'User not found');API
| 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() |
Development
npm install
npm run build
npm testSupport
If you find this project useful:
