@guanghechen/invariant
v7.0.2
Published
A simple invariant function
Readme
A simple invariant function that throws an error when the given condition fails. Error messages are
stripped in production builds (NODE_ENV === 'production') for smaller bundle size.
Install
npm
npm install --save @guanghechen/invariantyarn
yarn add @guanghechen/invariant
Usage
Basic Usage
import invariant from '@guanghechen/invariant'
function divide(a: number, b: number): number {
invariant(b !== 0, 'Division by zero is not allowed')
return a / b
}
divide(10, 2) // 5
divide(10, 0) // throws Error: "Invariant failed: Division by zero is not allowed"With Lazy Message
Use a function for expensive message computation:
import { invariant } from '@guanghechen/invariant'
function processUser(user: User | null) {
invariant(user !== null, () => `User not found: ${JSON.stringify(context)}`)
// TypeScript now knows `user` is not null
return user.name
}TypeScript Type Narrowing
The function uses asserts condition for proper type narrowing:
import invariant from '@guanghechen/invariant'
function getValue(map: Map<string, number>, key: string): number {
const value = map.get(key)
invariant(value !== undefined, `Key "${key}" not found in map`)
// TypeScript knows `value` is `number` here, not `number | undefined`
return value
}API
function invariant(
condition: boolean,
message?: string | (() => string) | null,
): asserts conditioncondition: The condition to assert. If falsy, an error is thrown.message: Optional error message (string or function returning string).
Reference
- homepage
- Inspired by tiny-invariant
