Skip to content

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 ​

ParameterTypeDescription
schemaSchema<T>The schema for the value when it is present
defaultT | (() => T)A default value or a function returning it

Notes ​

  • null is not a missing value — use nullable for it. To allow both: optional(nullable(string())).
  • Without default, the field in object becomes optional in the type (name?: string) and is not added to data when missing.
  • For arrays and objects pass a function: optional(array(string()), () => []). Otherwise all results share the same array.
  • Wrap pipe from the outside: optional(pipe(string(), email())). The other way round — pipe(optional(...), email()) — TypeScript rejects, because email can't handle undefined.

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' }

See also ​