undefinedable
Creates an undefinedable schema.
const Schema = v.undefinedable<TWrapped, TDefault>(wrapped, default_);
Generics
TWrappedextends BaseSchema<unknown, unknown, BaseIssue<unknown>>TDefaultextends Default<TWrapped, undefined>
Parameters
wrappedTWrappeddefault_TDefault
Explanation
With undefinedable the validation of your schema will pass undefined inputs, and if you specify a default_ input value, the schema will use it if the input is undefined. For this reason, the output type may differ from the input type of the schema.
undefinedablebehaves exactly the same asoptionalat runtime. The only difference is the input and output type when used for object entries. Whileoptionaladds a question mark to the key,undefinedabledoes not.Note that
undefinedabledoes not acceptnullas an input. If you want to acceptnullinputs, usenullable, and if you want to acceptnullandundefinedinputs, usenullishinstead. Also, if you want to set a default output value for any invalid input, you should usefallbackinstead.
Returns
SchemaUndefinedableSchema<TWrapped, TDefault>
Examples
The following examples show how undefinedable can be used.
Undefinedable string schema
Schema that accepts string and undefined.
const UndefinedableStringSchema = v.undefinedable(
v.string(),
"I'm the default!"
);
Undefinedable date schema
Schema that accepts Date and undefined.
By using a function as the
default_parameter, the schema will return a newDateinstance each time the input isundefined.
const UndefinedableDateSchema = v.undefinedable(v.date(), () => new Date());
Undefinedable entry schema
Object schema with an undefinedable entry.
const UndefinedableEntrySchema = v.object({
key: v.undefinedable(v.string()),
});
Unwrap undefinedable schema
Use unwrap to undo the effect of undefinedable.
const UndefinedableNumberSchema = v.undefinedable(v.number());
const NumberSchema = v.unwrap(UndefinedableNumberSchema);
Related
The following APIs can be combined with undefinedable.
Schemas
any, array, bigint, blob, boolean, custom, date, enum, exactOptional, file, function, instance, intersect, lazy, literal, looseObject, looseTuple, map, nan, never, nonNullable, nonNullish, null, nullable, nullish, number, object, objectWithRest, picklist, promise, record, set, strictObject, strictTuple, string, symbol, tuple, tupleWithRest, undefined, undefinedable, union, unknown, variant, void
Methods
assert, config, fallback, getDefault, getDefaults, getFallback, getFallbacks, is, message, parse, parser, pipe, safeParse, safeParser, unwrap
Actions
check, brand, description, flavor, guard, metadata, partialCheck, rawCheck, rawTransform, readonly, title, transform
Utils
entriesFromList, isOfKind, isOfType
© Fabian Hiller
Licensed under the MIT License.
https://valibot.dev/api/undefinedable/