# @epic-web/invariant 中文文档

规范地址：https://npmcn.com/package/%40epic-web/invariant/

版本：1\.0\.0
npm 元数据更新时间：2024-08-22T17:27:43.858Z
中文译文更新时间：2026-11-13T19:33:06.097Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40epic-web/invariant
原文对照：https://npmcn.com/package/%40epic-web/invariant/?lang=original
项目主页：https://github.com/epicweb-dev/invariant#readme
源码仓库：https://github.com/epicweb-dev/invariant

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：10.8 kB，4 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2023-12-14T00:28:05.151Z
- 最新版本发布：2023-12-14T00:28:05.418Z
- 近 30 天下载量：41958948（2026-10-14 至 2026-11-12，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

如果情况不妙, 受npm.im/invatant启发

## 安装

```sh
npm install @epic-web/invariant
```

也可以使用：`pnpm add @epic-web/invariant`、`yarn add @epic-web/invariant`、`bun add @epic-web/invariant`

## README

# [@epic-web/invatant (原始内容存档于2012-12-04)](https://npm.im/@epic-web/invariant)

**当事情不对时就抛出错误.**

特殊情况下投出错误(和答复)的安全设施类型 以宣示方式出现的情况.

```
npm install @epic-web/invariant
```

[![](https://github-production-user-asset-6210df.s3.amazonaws.com/1500684/257881576-fd66040b-679f-4f25-b0d0-ab886a14909a.png)](https://www.epicweb.dev/)

* * *

[![Build Status](https://img.shields.io/github/actions/workflow/status/epicweb-dev/invariant/release.yml?branch=main&logo=github&style=flat-square)](https://github.com/epicweb-dev/invariant/actions?query=workflow%3Arelease) [![MIT License](https://img.shields.io/badge/license-MIT%20License-blue.svg?style=flat-square)](https://github.com/epicweb-dev/invariant/blob/main/LICENSE) [![Code of Conduct](https://img.shields.io/badge/code%20of-conduct-ff69b4.svg?style=flat-square)](https://kentcdodds.com/conduct)

## 问题

您的申请有边界 。 网络请求/答复,文件系统读取, 包括: 当你用这些界限工作的时候,你需要能够处理 即使在 TypeScript 中也可能发生错误.

TypeScript 通常会让这些边界更加明显,因为它 不喜欢不知道是什么类型的东西。 例如:

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

通常使用一个适当的解析库 来应对这样的情况, 但对于简单的案件, 往往会觉得过度杀戮。 但你不想这样 忽略 TypeScript 是因为:

> TypeScript 是那个残忍的诚实朋友 你忍受,因为他们拯救 你犯过可怕的错误 [@ kentcdods (英语)](https://twitter.com/kentcdodds/status/1715562350835855396)

你检查一下:

```ts
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)
```

你在这里抛出一个描述错误是好的,因为它只是 _非常喜欢_ 可能性 这种事会发生的 即使你不知道该怎么做 说到这里.

这没什么大不了的 但有一小块锅炉板 避开。 特别是当你发现自己在代码库里做这一切时 这个 问题是 `@epic-web/invariant` 解说.

## 解决办法

这是上面的线索:

```diff
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)
```

很简单 但老实说,读起来更好,它扔一个特殊的 `InvariantError` 反对将其与其他类型的错误区分开来,我们 还有一个有用的工具来扔 `Response` 对象代替 `Error` 方便对象 [在重混合中](https://remix.run/docs/en/main/route/loader#throwing-responses-in-loaders)。 。 。 .

## 使用量

### `invariant`

这个 `invariant` 函数用来断言一个条件是真的。 如果 条件不正确, 它会与所提供消息发生错误 .

**基本用途**

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

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

**对虚假条件提出回应**

```ts
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
```

**使用回调错误消息**

```ts
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`

这个 `invariantResponse` 函数工作类似 `invariant`,但改为 抛出一个 `InvariantError`,它会扔出一个响应对象.

**基本用途**

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

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

**对虚假条件提出回应**

```ts
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' }
```

如果有400个响应状态默认( Bad Request), 但你会找到如何改变 下面那个.

**使用回调响应信件**

```ts
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`,
)
```

**丢入附加选项的响应**

```ts
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' } },
)
```

## 与 [无变化](https://www.npmjs.com/package/invariant)

有三种主要差别. 与 `@epic-web/invariant`数字 :

1.  Dev 和 prod 中错误消息相同
2.  这很安全
3.  我们也支持(反正雷米克) 提出回应的普通案例 与 `invariantResponse`。 。 。 .

## 许可证

麻省理工学院

## 常见问题

### @epic-web/invariant 是什么？

如果情况不妙, 受npm\.im/invatant启发

### 如何安装 @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 和提交记录判断。

