@epic-web/invariant

中文文档
1.0.0发布于 2023/12/14MITTypeScriptES Module零依赖近 30 天下载 4195.9万

Type safe utilities for throwing errors (and responses) if things aren't quite right. Inspired by npm.im/invariant

原始使用文档
文档目录7 节
  1. The Problem
  2. The Solution
  3. Usage
  4. invariant
  5. invariantResponse
  6. Differences from invariant
  7. License

💥 @epic-web/invariant

Throw errors when thing's aren't right.

Type safe utilities for throwing errors (and responses) in exceptional situations in a declarative way.

npm install @epic-web/invariant

Build Status MIT License Code of Conduct

The Problem

Your application has boundaries. Network requests/responses, file system reads, etc. When you're working with these boundaries, you need to be able to handle errors that may occur, even in TypeScript.

TypeScript will typically make these boundaries much more obvious because it doesn't like not knowing what the type of something is. For example:

const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`

Often it's a good idea to use a proper parsing library for situations like this, but for simple cases that can often feel like overkill. But you don't want to just ignore TypeScript because:

TypeScript is that brutally honest friend you put up with because they save you from making terrible mistakes. – @kentcdodds

So you check it:

const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`
if (typeof name !== 'string') {
    throw new Error('Name must be a string')
}
// now name is `string` (and TypeScript knows it too)

You're fine throwing a descriptive error here because it's just very unlikely this will ever happen and even if it does you wouldn't really know what to do about it anyway.

It's not a big deal, but there's a tiny bit of boilerplate that would be nice to avoid. Especially when you find yourself doing this all over the codebase. This is the problem @epic-web/invariant solves.

The Solution

Here's the diff from what we had above:

const formData = new FormData(formElement)
const name = await formData.get('name')
// name is `File | string | null`
- if (typeof name !== 'string') {
- 	throw new Error('Name must be a string')
- }
+ invariant(typeof name === 'string', 'Name must be a string')
// now name is `string` (and TypeScript knows it too)

It's pretty simple. But honestly, it's nicer to read, it throws a special InvariantError object to distinguish it from other types of errors, and we have another useful utility for throwing Response objects instead of Error objects which is handy in Remix.

Usage

invariant

The invariant function is used to assert that a condition is true. If the condition is false, it throws an error with the provided message.

Basic Usage

import { invariant } from '@epic-web/invariant'

const creature = { name: 'Dragon', type: 'Fire' }
invariant(creature.name === 'Dragon', 'Creature must be a Dragon')

Throwing a Response on False Condition

import { invariant } from '@epic-web/invariant'

const creature = { name: 'Unicorn', type: 'Magic' }
invariant(creature.type === 'Fire', 'Creature must be of type Fire')
// Throws: InvariantError: Creature must be of type Fire

Using Callback for Error Message

import { invariantResponse } from '@epic-web/invariant'

const creature = { name: 'Elf', type: 'Forest' }
invariant(creature.type === 'Water', () => 'Creature must be of type Water')
// Throws: InvariantError: Creature must be of type Water

invariantResponse

The invariantResponse function works similarly to invariant, but instead of throwing an InvariantError, it throws a Response object.

Basic Usage

import { invariantResponse } from '@epic-web/invariant'

const creature = { name: 'Phoenix', type: 'Fire' }
invariantResponse(creature.type === 'Fire', 'Creature must be of type Fire')

Throwing a Response on False Condition

import { invariantResponse } from '@epic-web/invariant'

const creature = { name: 'Griffin', type: 'Air' }
invariantResponse(creature.type === 'Water', 'Creature must be of type Water')
// Throws: Response { status: 400, body: 'Creature must be of type Water' }

The response status default if 400 (Bad Request), but you'll find how to change that below.

Using Callback for Response Message

import { invariantResponse } from '@epic-web/invariant'

const creature = { name: 'Mermaid', type: 'Water' }
invariantResponse(
    creature.type === 'Land',
    () => `Expected a Land creature, but got a ${creature.type} creature`,
)

Throwing a Response with Additional Options

import { invariantResponse } from '@epic-web/invariant'

const creature = { name: 'Cerberus', type: 'Underworld' }
invariantResponse(
    creature.type === 'Sky',
    JSON.stringify({ error: 'Creature must be of type Sky' }),
    { status: 500, headers: { 'Content-Type': 'text/json' } },
)

Differences from invariant

There are three main differences. With @epic-web/invariant:

  1. Error messages are the same in dev and prod
  2. It's typesafe
  3. We support the common case (for Remix anyway) of throwing Responses as well with invariantResponse.

License

MIT

版本与发布记录

@epic-web/invariant 共发布 1 个版本,首次发布于 2023/12/14;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.0latest2023/12/142 年前

关于 @epic-web/invariant 的常见问题

@epic-web/invariant 是什么?

Type safe utilities for throwing errors (and responses) if things aren't quite right. Inspired by npm.im/invariant

如何安装 @epic-web/invariant?

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

@epic-web/invariant 支持 TypeScript 吗?

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

@epic-web/invariant 支持 ESM 还是 CommonJS?

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

@epic-web/invariant 可以商用吗?

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

@epic-web/invariant 的下载量有多少?

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

@epic-web/invariant 还在维护吗?

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