Optionals
您好!Valibot 提供了 optional、exactOptional、undefinedable、nullable 和 nullish 模式,作为处理可选值的便捷方式。这些模式可以让你在接受特定值的同时,也接受 undefined 或 null,从而减少样板代码,并提高 API 的可读性。
工作原理
为了让你的模式除了实际值之外也接受 undefined 和/或 null,你只需用 optional、exactOptional、undefinedable、nullable 或 nullish 来包装你的模式。
注意:
exactOptional允许对象中缺少条目,但它不允许undefined作为指定值。*
import * as v from 'valibot';
const OptionalStringSchema = v.optional(v.string()); // string | undefined
const ExactOptionalStringSchema = v.exactOptional(v.string()); // string
const UndefinedableStringSchema = v.undefinedable(v.string()); // string | undefined
const NullableStringSchema = v.nullable(v.string()); // string | null
const NullishStringSchema = v.nullish(v.string()); // string | null | undefined
在对象中的使用
当在对象内部使用时,optional、exactOptional 和 nullish 是特殊情况,因为它们在 TypeScript 中也会用问号将值标记为可选。
import * as v from 'valibot';
const OptionalKeySchema = v.object({ key: v.optional(v.string()) }); // { key?: string | undefined }
默认值
optional、exactOptional、undefinedable、nullable 和 nullish 的独特之处在于,这些模式函数接受一个默认值作为第二个参数。根据模式函数的不同,当输入缺失、undefined 或 null 时,始终会使用这个默认值。
import * as v from 'valibot';
const OptionalStringSchema = v.optional(v.string(), "I'm the default!");
type OptionalStringInput = v.InferInput<typeof OptionalStringSchema>; // string | undefined
type OptionalStringOutput = v.InferOutput<typeof OptionalStringSchema>; // string
通过提供一个默认值,模式的输入类型现在与输出类型不同。在这个例子中,该模式接受 string 和 undefined 作为输入,但在两种情况下都返回 string 作为输出。
动态默认值
在某些情况下,需要动态生成默认值。为此,也可以将一个生成并返回默认值的函数作为第二个参数传递。
import * as v from 'valibot';
const NullableDateSchema = v.nullable(v.date(), () => new Date());
上面的例子为每个输入为 null 的验证创建一个新的 Date 实例,然后将其用作默认值。
依赖默认值
在极少数情况下,可选条目的默认值可能依赖于同一对象中另一个条目的值。这可以通过在对象的 pipe 中使用 transform 来实现。
import * as v from 'valibot';
const CalculationSchema = v.pipe(
v.object({
a: v.number(),
b: v.number(),
sum: v.optional(v.number()),
}),
v.transform((input) => ({
...input,
sum: input.sum === undefined ? input.a + input.b : input.sum,
}))
);