decoders

Objects

Object decoders for validating structured data.

object

object({ field1: Decoder<A>, field2: Decoder<B>, ... }): Decoder<{ field1: A, field2: B, ... }> (source)

Accepts objects with fields matching the given decoders. Extra fields that exist on the input object are ignored and will not be returned.

const decoder = object({
  x: number,
  y: number,
});

// 👍
decoder.verify({ x: 1, y: 2 }) === { x: 1, y: 2 };
decoder.verify({ x: 1, y: 2, z: 3 }) === { x: 1, y: 2 }; // ⚠️ extra field `z` not returned!

// 👎
decoder.verify({ x: 1 });  // throws, missing field `y`

For more information, see also The difference between object, exact, and inexact.


exact

exact({ field1: Decoder<A>, field2: Decoder<B>, ... }): Decoder<{ field1: A, field2: B, ... }> (source)

Like object(), but will reject inputs that contain extra fields that are not specified explicitly.

const decoder = exact({
  x: number,
  y: number,
});

// 👍
decoder.verify({ x: 1, y: 2 }) === { x: 1, y: 2 };

// 👎
decoder.verify({ x: 1, y: 2, z: 3 });  // throws, extra field `z` not allowed
decoder.verify({ x: 1 });              // throws, missing field `y`

For more information, see also The difference between object, exact, and inexact.


inexact

inexact({ field1: Decoder<A>, field2: Decoder<B>, ... }): Decoder<{ field1: A, field2: B, ... }> (source)

Like object(), but will pass through any extra fields on the input object unvalidated that will thus be of unknown type statically.

const decoder = inexact({
  x: number,
  y: number,
});

// 👍
decoder.verify({ x: 1, y: 2 }) === { x: 1, y: 2 };
decoder.verify({ x: 1, y: 2, z: 3 }) === { x: 1, y: 2, z: 3 };

// 👎
decoder.verify({ x: 1 });  // throws, missing field `y`

For more information, see also The difference between object, exact, and inexact.


pojo

pojo: Decoder<Record<string, unknown>> (source)

Accepts any "plain old JavaScript object", but doesn't validate its keys or values further.

// 👍
pojo.verify({}) === {};
pojo.verify({ name: 'hi' }) === { name: 'hi' };

// 👎
pojo.verify('hi');        // throws
pojo.verify([]);          // throws
pojo.verify(new Date());  // throws
pojo.verify(null);        // throws

On this page