@geektech/backone-utils
Schema 校验
zod 风格轻量校验器:类型推导、safeParse 与 v 工厂。
schema 模块是 zod 风格的轻量校验器:通过 v 工厂构建 schema,支持类型推导(InferType)与 safeParse,零运行时依赖。
基本用法
ts
import { v, ValidationError } from '@geektech/backone-utils';
const userSchema = v.object({
name: v.string({ minLength: 2, maxLength: 32 }),
age: v.number({ integer: true, min: 0, max: 150 }),
email: v.string({ pattern: /^[^@]+@[^@]+$/ }),
role: v.enum(["admin", "user"] as const),
});
type User = InferType<typeof userSchema>; // 类型自动推导
const parsed = userSchema.safeParse({ name: 'alice', age: 30, email: 'a@b.co', role: 'admin' });
if (!parsed.success) {
console.error(parsed.error.issues); // 结构化问题列表
}v 工厂一览
| 方法 | 说明 |
|---|---|
v.string(options) | 字符串:minLength / maxLength / pattern |
v.number(options) | 数字:min / max / integer |
v.boolean() | 布尔 |
v.literal(value) | 字面量:仅接受指定值 |
v.enum(values) | 枚举 |
v.array(item, options) | 数组:元素 schema + 长度约束 |
v.object(shape) | 对象:形状校验,返回类型化对象 |
v.record(value) | 记录:任意字符串键 → 同构值 |
v.optional(schema) | 可选:undefined 通过 |
v.nullable(schema) | 可空:null 通过 |
v.union(schemas) | 联合 |
safeParse
| 字段 | 说明 |
|---|---|
success | 是否通过 |
data | 通过时的类型化数据 |
error | 失败时的 ValidationError,含 issues 列表与格式化路径 |
提示
可以结合 config 模块使用:defineConfig 内部就用 v 的 object schema 做配置校验。见全局配置。