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.
| Input | Result |
|---|---|
| … | |
| … | |
| … | |
| … | |
| … |
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.
| Input | Result |
|---|---|
| … | |
| … | |
| … | |
| … | |
| … |
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 datenullish
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.
| Input | Result |
|---|---|
| … | |
| … | |
| … | |
| … | |
| … |
Or use it with a default value:
const decoder = nullish(string, null);
decoder.verify('hello') === 'hello';
decoder.verify(null) === null;
decoder.verify(undefined) === null;