Optional
Decoders for handling optional and nullable values.
optional
function optional( decoder: Decoder<T> ): Decoder<T | undefined> (source)
function optional( decoder: Decoder<T>, default: V ): Decoder<T | V>
function optional( decoder: Decoder<T>, default: () => V ): Decoder<T | V>
Accepts whatever the given decoder accepts, or undefined.
If a default value is explicitly provided, return that instead in the undefined case.
Try it
| Input | Result |
|---|---|
| "hello" | |
| undefined | |
| null ^^^^ Either: - Must be undefined - Must be string | |
| 0 ^ Either: - Must be undefined - Must be string | |
| 42 ^^ Either: - Must be undefined - Must be string |
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
function nullable( decoder: Decoder<T> ): Decoder<T | null> (source)
function nullable( decoder: Decoder<T>, default: V ): Decoder<T | V>
function nullable( decoder: Decoder<T>, default: () => V ): Decoder<T | V>
Accepts whatever the given decoder accepts, or null.
If a default value is explicitly provided, return that instead in the null case.
Try it
| Input | Result |
|---|---|
| "hello" | |
| null | |
| undefined ^^^^^^^^^ Either: - Must be null - Must be string | |
| 0 ^ Either: - Must be null - Must be string | |
| 42 ^^ Either: - Must be null - Must be string |
Or use it with a default value:
const decoder = nullable(isoDate, () => new Date());
decoder.verify('2022-01-01T12:00:00Z') === '2022-01-01T12:00:00Z';
decoder.verify(null); // the current datenullish
function nullish( decoder: Decoder<T> ): Decoder<T | null | undefined> (source)
function nullish( decoder: Decoder<T>, default: V ): Decoder<T | V>
function nullish( decoder: Decoder<T>, default: () => V ): Decoder<T | V>
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
| Input | Result |
|---|---|
| "hello" | |
| null | |
| undefined | |
| 0 ^ Either: - Must be undefined or null - Must be string | |
| 42 ^^ Either: - Must be undefined or null - Must be string |
Or use it with a default value:
const decoder = nullish(string, null);
decoder.verify('hello') === 'hello';
decoder.verify(null) === null;
decoder.verify(undefined) === null;