Skip to content

TypeScript ​

tinyval 使用 TypeScript 编写。数据类型从 Schema 推导而来,无需另外声明接口。

Infer —— 从 Schema 获取类型 ​

ts
import { object, string, number, optional, array, oneOf, type Infer } from 'tinyval';

const User = object({
  name: string(),
  age: optional(number()),
  role: oneOf(['admin', 'user']),
  tags: array(string()),
});

type User = Infer<typeof User>;
// {
//   name: string;
//   role: 'admin' | 'user';
//   tags: string[];
//   age?: number | undefined;
// }

用 optional 包裹且没有默认值的字段会变为可选(?)。使用 transform 时,类型为转换后的结果。

收窄结果类型 ​

validate 返回联合类型:检查 valid 之后,TypeScript 就知道是否存在 data:

ts
const result = validate(User, input);

if (result.valid) {
  result.data.name; // string
} else {
  result.data;      // undefined
  result.errors;    // Record<string, string>
}

parse 直接返回 Infer<typeof User>。

规则兼容性检查 ​

规则必须与 Schema 类型匹配 —— 运行之前就能看到错误:

ts
pipe(number(), minLength(2)); // 错误:minLength 用于字符串和数组
pipe(string(), min(1));       // 错误:min 用于数字

自定义检查中的类型 ​

可以显式指定 check 的值类型:

ts
const even = check<number>((v) => v % 2 === 0, '必须是偶数');

导出的类型 ​

类型说明
Schema<T>返回 T 类型值的 Schema
Infer<S>Schema S 的数据类型
Result<T>validate 的结果
Issue错误:{ code, message, path, params }
Message字符串或函数 (params) => string
Options校验选项:{ all?, abortEarly?, messages?, labels?, maxDepth? } —— 见 validate
Action<T>pipe 的规则或转换
Infocheck 的第二个参数:{ parent, root }

另请参阅 ​