用途
no-bare-casts 是 prisma/prisma-next 中针对生产 TypeScript/TSX 代码的类型断言约束规则。它把裸 as 视为需要停下并重新评估类型设计的信号,而不是随手可用的默认手段。
主要能力
规则要求,在生产代码中写入或保留裸 as 之前,必须先按决策树依次判断:
- 收紧输入类型:能否让源处的参数、泛型边界或返回类型更具体,从而不再需要断言。
- 增加运行时检查:能否通过类型谓词(如
function isUser(x): x is User)在运行时收窄类型,消除断言。 - 重构泛型:能否用边界或约束携带所需信息,使断言不再必要。
- 使用
satisfies:expr satisfies T会检查类型而不强制转换,适合只想做类型检查而非类型强转的场景。 - 使用
castAs<T>(value):当值在运行时已经满足 T,断言纯属声明性质时使用。 - 仅当以上都不适用时,才使用
blindCast<T, "Reason">(value)。
使用方式
从 @prisma-next/utils/casts 导入辅助函数:
import { blindCast, castAs } from '@prisma-next/utils/casts';
辅助函数签名:
// Escape hatch — the value is genuinely opaque or unrelated to the target type.
// The Reason literal documents the compromise; the reviewer evaluates it.
function blindCast<TargetType, Reason extends string>(input: unknown): TargetType
// Declarative assertion — the value already satisfies T at runtime.
function castAs<T>(value: T): T
blindCast 是最后手段,不是便利包装。它的第二个类型参数必须是审查者可据以行动的字符串字面量,例如:
// ✅ Names the specific constraint
blindCast<User, "deserialized from contract validator; shape has already been checked">(raw)
// ❌ Adds no information — reviewer has nothing to evaluate
blindCast<User, "trust me">(raw)
含糊的理由是审查者提出质疑的信号,也是作者重新审视类型设计的信息。
此外规则要求“触及时即转换”:当修改的文件中含有裸 as 断言时,即便只是无关工作的一部分,也应将其转换为被接受的形式或消除。CI 检查(pnpm lint:casts)会拒绝每个 PR 中类型断言数量的增加,通过持续转换逐步减少总量。
适用场景与限制
适用于需要在生产 TypeScript 代码中控制类型断言、提升类型安全性的项目。测试文件(.test.ts、.test.d.ts、test/**/*.ts)豁免此规则——测试中使用 as 做打桩和类型断言是允许的。本工具所在项目的具体平台支持、收费方式、价格与效果暂未提供。