decoders

Collections

Decoders for records, maps, and sets.

record

record(values: Decoder<V>): Decoder<Record<string, V>> (source)

record(keys: Decoder<K>, values: Decoder<V>): Decoder<Record<K, V>> (source)

Accepts objects where all values match the given decoder, and returns the result as a Record<string, V>.

This is useful to validate inputs like { [key: string]: V }.

Decoding values only

The default call takes a single argument and will validate all values. For example, to validate that all values in the object are numbers:

const decoder = record(number);
//                        \
//                      Values must be numbers

// 👍
decoder.verify({ red: 1, blue: 2, green: 3 });

// 👎
decoder.verify({ hi: 'not a number' });

Decoding keys and values

If you also want to validate that keys are of a specific form, use the two-argument form: record(key, value). Note that the given key decoder must return strings.

For example, to enforce that all keys are emails:

const decoder = record(email, number);
//                      /        \
//              Keys must        Values must
//             be emails           be numbers

// 👍
decoder.verify({ "me@nvie.com": 1 });

// 👎
decoder.verify({ "no-email": 1 });

mapping

mapping(decoder: Decoder<T>): Decoder<Map<string, T>> (source)

Similar to record(), but returns the result as a Map<string, T> (an ES6 Map) instead.

const decoder = mapping(number);

// 👍
decoder.verify({ red: 1, blue: 2, green: 3 });
// Map([
//   ['red', '1'],
//   ['blue', '2'],
//   ['green', '3'],
// ]);

setFromArray

setFromArray(decoder: Decoder<T>): Decoder<Set<T>> (source)

Similar to array(), but returns the result as an ES6 Set.

const decoder = setFromArray(string);

// 👍
decoder.verify(['abc', 'pqr'])  // new Set(['abc', 'pqr'])
decoder.verify([])              // new Set([])

// 👎
decoder.verify([1, 2]);         // throws, not the right types

On this page