@crutchcrew/invariant

中文文档
1.1.1发布于 2026/09/12MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 8775

Yet another tiny invariant package for your TypeScript project

原始使用文档
文档目录14 节
  1. How it works
  2. Why this package
  3. Install
  4. Usage
  5. Lazy messages
  6. Custom errors
  7. Console methods
  8. Strict typing
  9. API
  10. invariant(condition, message?)
  11. createInvariant(ErrorClass)
  12. InvariantError
  13. Development
  14. Credits

invariant 🔬🔨

npm version gzip size coverage provenance license

TypeScript invariant with custom error class support — tiny as tiny-invariant, type-safe as ts-invariant, versatile as nothing else.

How it works

An invariant function takes a value and throws if the value is falsy. If the value is truthy, execution continues and TypeScript narrows the type.

import { invariant } from "@crutchcrew/invariant"

const user: User | null = getUser()
invariant(user, "User not found")
console.log(user.name) // user is narrowed to User

Why this package

This packagetiny-invariantts-invariantinvariant
Size (gzip)~364 B~370 B~1.0 kB~1.1 kB
Zero Dependencies✅✅❌❌
Tree-shakeable ESM✅✅✅❌
Type narrowing✅✅✅❌
Strict typing✅❌❌❌
Lazy messages✅❌❌❌
Console methods✅❌✅❌
Invariant factory✅❌❌❌

Install

Choose your fighter 🥊

pnpm add @crutchcrew/invariant
bun add @crutchcrew/invariant
yarn add @crutchcrew/invariant
npm add @crutchcrew/invariant

Usage

const response = await fetch("/users/1")
invariant(response.ok, `Request failed: ${response.status}`)

const user = await response.json()

Lazy messages

Pass a function to defer message construction and avoid expensive message computation

invariant(value, getExpensiveMessage)

Custom errors

If you need to throw domain-specific errors — a NotFoundError, a ValidationError, or anything else — you're left wrapping calls or rolling your own helper. This package provides createInvariant to build an invariant function that throws any error class you give it, with the same assertion narrowing and lazy message support.

Use createInvariant to throw your own error type:

import { createInvariant } from "@crutchcrew/invariant"

class HttpError extends Error {
    name = "HttpError"
}

const invariant = createInvariant(HttpError)

export async function getUser(id: string) {
    const response = await fetch(`/users/${id}`)
    invariant(response.ok, `Request failed: ${response.status}`)

    return response.json()
}

Console methods

The invariant function exposes debug, log, warn, and error methods that delegate to the corresponding console methods:

invariant.debug(`Message ${id} sent`)
invariant.log("User", user)
invariant.warn("Unexpected state", { detail })
invariant.error("Something went wrong")

Strict typing

The default invariant allows to pass any value as a condition so it can check on any truthy/falsy value — objects, strings, numbers, whatever you hand it. Import from @crutchcrew/invariant/strict instead to require an actual boolean, catching accidental truthy/falsy checks at the type level:

import { invariant } from "@crutchcrew/invariant/strict"

invariant(user !== null, "User not found") // ✅ boolean condition
invariant(user, "User not found") // ❌ type error: User | null is not assignable to boolean

It's the same runtime as the regular invariant — just a stricter type layer — so createInvariant and InvariantError are also available from /strict.

API

invariant(condition, message?)

// default
(condition: unknown, message?: string | (() => string)) => asserts condition
// strict
(condition: boolean, message?: string | (() => string)) => asserts condition

Throws InvariantError if condition is falsy. Narrows the type of condition to truthy.

createInvariant(ErrorClass)

;<E extends Error>(ErrorClass: new (message: string) => E) => Invariant

Returns a new invariant function that throws ErrorClass instead of InvariantError.

InvariantError

Default error class thrown by invariant. Extends Error with framesToPop = 1 for cleaner stack traces.

Development

bun install
bun test
bun run check    # fmt + lint (with type-check) in parallel

Credits

The API and InvariantError design are based on ts-invariant by Ben Newman and the Apollo team. The /strict entry point is inspired by ts-tiny-invariant by Igor Yegoroff.

版本与发布记录

@crutchcrew/invariant 共发布 5 个版本,首次发布于 2026/09/12;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.1latest2026/09/121 个月前
1.1.02026/09/121 个月前
1.0.02026/09/121 个月前
0.1.12026/09/121 个月前
0.1.02026/09/121 个月前

关于 @crutchcrew/invariant 的常见问题

@crutchcrew/invariant 是什么?

Yet another tiny invariant package for your TypeScript project

如何安装 @crutchcrew/invariant?

在项目目录运行 npm install @crutchcrew/invariant,或使用 pnpm add / yarn add / bun add。

@crutchcrew/invariant 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@crutchcrew/invariant 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@crutchcrew/invariant 可以商用吗?

@crutchcrew/invariant 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@crutchcrew/invariant 的下载量有多少?

根据 npm 官方下载统计,@crutchcrew/invariant 在 2026/10/11 – 2026/11/09 这 30 天内被下载 8,775 次,日均约 293 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@crutchcrew/invariant 还在维护吗?

最新版本 1.1.1 发布于 2026/09/12(1 个月前);至今共发布 5 个版本,其中过去 12 个月发布了 5 个;首次发布于 2026/09/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。