optional
Makes a value optional. If the value is missing (undefined) or an empty string (''), validation is skipped and the default value is used.
Signature
ts
function optional<T>(schema: Schema<T>): Schema<T | undefined>
function optional<T>(schema: Schema<T>, default: T | (() => T)): Schema<T>Parameters
| Parameter | Type | Description |
|---|---|---|
schema | Schema<T> | The schema for the value when it is present |
default | T | (() => T) | A default value or a function returning it |
Notes
nullis not a missing value — usenullablefor it. To allow both:optional(nullable(string())).- Without
default, the field inobjectbecomes optional in the type (name?: string) and is not added todatawhen missing. - For arrays and objects pass a function:
optional(array(string()), () => []). Otherwise all results share the same array. - Wrap
pipefrom the outside:optional(pipe(string(), email())). The other way round —pipe(optional(...), email())— TypeScript rejects, becauseemailcan't handleundefined.
Example
Optional fields
ts
const Profile = object({
name: string(),
website: optional(pipe(string(), pattern(/^https?:\/\//))),
lang: optional(oneOf(['ru', 'en']), 'en'),
});
validate(Profile, { name: 'Ann', website: '' }).data; // { name: 'Ann', lang: 'en' }