npm.io
7.0.4 • Published 2 months ago

@guanghechen/invariant

Licence
MIT
Version
7.0.4
Deps
0
Size
8 kB
Vulns
0
Weekly
0

@guanghechen/invariant


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/invariant
  • yarn

    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 condition
  • condition: The condition to assert. If falsy, an error is thrown.
  • message: Optional error message (string or function returning string).

Reference