decoders

Optional

Decoders for handling optional and nullable values.

optional

optional( decoder: Decoder<T> ): Decoder<T | undefined> (source)

optional( decoder: Decoder<T>, defaultValue: V | (() => V) ): Decoder<T | V> (source)

Accepts whatever the given decoder accepts, or undefined.

If a default value is explicitly provided, return that instead in the undefined case.

Try it
optional(string).verify('hello')
InputResult

A typical case where optional() is useful is in decoding objects with optional fields:

object({
  id: number,
  name: string,
  address: optional(string),
});

Which will decode to type:

{
  id: number;
  name: string;
  address?: string;
}

nullable

nullable( decoder: Decoder<T> ): Decoder<T | null> (source)

nullable( decoder: Decoder<T>, defaultValue: V | (() => V) ): Decoder<T | V> (source)

Accepts whatever the given decoder accepts, or null.

If a default value is explicitly provided, return that instead in the null case.

Try it
nullable(string).verify('hello')
InputResult

Or use it with a default value:

const decoder = nullable(iso8601, () => new Date());

decoder.verify('2022-01-01T12:00:00Z') === '2022-01-01T12:00:00Z';
decoder.verify(null); // the current date

nullish

nullish( decoder: Decoder<T> ): Decoder<T | null | undefined> (source)

nullish( decoder: Decoder<T>, defaultValue: V | (() => V) ): Decoder<T | V> (source)

Accepts whatever the given decoder accepts, or null, or undefined.

If a default value is explicitly provided, return that instead in the null/undefined case.

Try it
nullish(string).verify('hello')
InputResult

Or use it with a default value:

const decoder = nullish(string, null);

decoder.verify('hello') === 'hello';
decoder.verify(null) === null;
decoder.verify(undefined) === null;

On this page