类型推导
除了能够推断输入和输出类型之外,模式还有一个很酷的特性。这让你的工作变得更加轻松,因为你无需自己编写类型定义。
推断输入类型
模式的输入类型对应于传入数据必须匹配的 TypeScript 类型,以便其有效。要提取此类型,可以使用实用工具类型 InferInput。
你可能只在特殊情况下对输入类型感兴趣。在大多数情况下,输出类型就足够了。
import * as v from 'valibot';
const LoginSchema = v.object({
email: v.string(),
password: v.string(),
});
type LoginInput = v.InferInput<typeof LoginSchema>; // { email: string; password: string }
推断输出类型
只有当你在验证后使用带有默认值的 optional、nullable、nullish 或 undefinedable,或者使用 brand、readonly 或 transform 来转换模式的输入或数据类型时,输出类型才与输入类型不同。输出类型对应于 parse 和 safeParse 的输出。要推断它,可以使用实用工具类型 InferOutput。
import * as v from 'valibot';
import { hashPassword } from '~/utils';
const LoginSchema = v.pipe(
v.object({
email: v.string(),
password: v.pipe(v.string(), v.transform(hashPassword)),
}),
v.transform((input) => {
return {
...input,
timestamp: new Date().toISOString(),
};
})
);
type LoginOutput = v.InferOutput<typeof LoginSchema>; // { email: string; password: string; timestamp: string }
推断问题类型
你还可以推断模式可能遇到的问题类型。如果你想以特定方式处理这些问题,这会非常有用。要从模式中提取此信息,可以使用实用工具类型 InferIssue。
import * as v from 'valibot';
const LoginSchema = v.object({
email: v.pipe(v.string(), v.email()),
password: v.pipe(v.string(), v.minLength(8)),
});
type Issue = v.InferIssue<typeof LoginSchema>; // v.ObjectIssue | v.StringIssue | v.EmailIssue<string> | v.MinLengthIssue<string, 8>