变化无常
有自定义错误类支持的 TypeScript 不变量 – 微小为 tiny-invariant,类型安全为 ts-invariant多才多艺,别无他法.
如何运作
import { invariant } from "@crutchcrew/invariant"
const user: User | null = getUser()
invariant(user, "User not found")
console.log(user.name) // user is narrowed to User
为什么这个包
| 这个包 | 微小变化性 | ts-invatant(变异) | 无变化 | |
|---|---|---|---|---|
| 大小( gzip) | 约364 B | ~370个B级 | ~1.0千贝 | ~1.1 kB (千位点) |
| 无依赖 | ✅ | ✅ | ❌ | ❌ |
| 树能变化的无害环境管理 | ✅ | ✅ | ✅ | ❌ |
| 类型缩小 | ✅ | ✅ | ✅ | ❌ |
| 严格打字 | ✅ | ❌ | ❌ | ❌ |
| 懒散消息 | ✅ | ❌ | ❌ | ❌ |
| 控制台方法 | ✅ | ❌ | ✅ | ❌ |
| 工厂 | ✅ | ❌ | ❌ | ❌ |
安装
选择你的格斗家
pnpm add @crutchcrew/invariant
bun add @crutchcrew/invariant
yarn add @crutchcrew/invariant
npm add @crutchcrew/invariant
使用量
const response = await fetch("/users/1")
invariant(response.ok, `Request failed: ${response.status}`)
const user = await response.json()
懒散消息
通过一个函数来推迟消息构建并避免昂贵的消息计算
invariant(value, getExpensiveMessage)
自定义错误
如果您需要丢弃特定域的错误—— a NotFoundError页:1 ValidationError或者是别的什么... ...你被留下来打包电话或者滚出自己的助手 此软件包提供 createInvariant 来构建一个不变量的函数,将您给出的任何错误类都抛出,同时同样的断言缩小和懒散的信息支持.
使用 createInvariant 来抛出自己的错误类型 :
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()
}
控制台方法
变异函数暴露 debug, (中文(简体) ), log, (中文(简体) ), warn,以及 error 向相应机构授权的方法 console 方法:
invariant.debug(`Message ${id} sent`)
invariant.log("User", user)
invariant.warn("Unexpected state", { detail })
invariant.error("Something went wrong")
严格打字
默认的变量允许通过任何值作为条件,这样它就可以检查任何真实/虚伪值——对象,字符串,数字,无论你交出它什么. 从 @crutchcrew/invariant/strict 而不是要求实际 boolean,在类型级别进行意外的真相/虚假检查:
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
它和普通的无变体一样的运行时间——只是更严格的类型层——所以 createInvariant 财务报告和审定财务报表 InvariantError 也可从下列网址获得: /strict。 。 。 .
API 密码
invariant(condition, message?)
// default
(condition: unknown, message?: string | (() => string)) => asserts condition
// strict
(condition: boolean, message?: string | (() => string)) => asserts condition
掷出 InvariantError 若为 condition 是恶作剧。 缩小类型 condition 说实话.
createInvariant(ErrorClass)
;<E extends Error>(ErrorClass: new (message: string) => E) => Invariant
返回丢出的新不变量函数 ErrorClass 改为 InvariantError。 。 。 .
InvariantError
被丢弃的默认错误类 invariant扩展 Error 与 framesToPop = 1 用于更干净的堆栈痕迹.
发展
bun install
bun test
bun run check # fmt + lint (with type-check) in parallel
贷项
API和 InvariantError 设计基于 ts-invatant(变异) 由本·纽曼和阿波罗团队出演. 这个 /strict 切入点灵感来自 ts-tiny-invatant 缩写 伊戈尔·叶戈罗夫著.