Skip to content

Array Decoders

The Course
•
20 min study

A combinator is a function that builds a bigger decoder from a smaller one. The example below builds field("pages", count): a decoder for an object's pages field, made from a decoder for one count. It reads the field, lets count judge the value, and on failure adds "pages" to the front of the issue path. count knows nothing about objects or field names, and field knows nothing about counts; that separation is what lets each be reused. at joins path parts, and leaf decoders such as count report an empty path.

Reflect.get(value, name) reads a property by a runtime name. Like JSON.parse, it returns any, so the result is bound straight to unknown.

A generic array decoder follows the same pattern: it applies one Decoder<T> to every input element and returns Result<readonly T[]>. If the outer value is not an array, it fails. If any element fails, it rejects the whole list and prefixes the issue path with that element's index.

Array.isArray narrows to any[] in TypeScript's standard library. Immediately bind each element to unknown before invoking domain logic; do not let that historical any become permission to read unchecked properties. The generic decoder only promises the values its element decoder has actually produced.

array.entries() supplies pairs of index and value. Destructure those pairs to build locations like 1.pages. This is a normal JavaScript array method; the tuple syntax from Day 2 explains why each position has a different role.

Do not return partial accepted data while claiming a full-list success. If partial acceptance is desired, design a different result that carries both accepted values and issues. This course chooses all-or-error for a small clear contract.

Predict, run, and explain

Write down what the program prints before you run it. Use Check types first; the program runs only when the real compiler accepts it.

Predict, then runTypeScript
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;

function at(prefix: string, path: string): string {
  return path === "" ? prefix : `${prefix}.${path}`;
}

const count: Decoder<number> = value =>
  typeof value === "number" && Number.isInteger(value) && value >= 0
    ? { ok: true, value }
    : { ok: false, issue: { path: "", message: "Expected count" } };

function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
  return value => {
    if (typeof value !== "object" || value === null) {
      return { ok: false, issue: { path: "", message: "Expected object" } };
    }
    const raw: unknown = Reflect.get(value, name);
    const result = decode(raw);
    if (result.ok) {
      return result;
    }
    return {
      ok: false,
      issue: { path: at(name, result.issue.path), message: result.issue.message }
    };
  };
}

const pages = field("pages", count);
const good = pages({ title: "Types", pages: 120 });
const bad = pages({ title: "Types", pages: -1 });

console.log(good.ok ? good.value : good.issue.path);
console.log(bad.ok ? bad.value : `${bad.issue.path}: ${bad.issue.message}`);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
120
pages: Expected count

Reject a whole list without leaking partial success

A list decoder combines a container rule with an element decoder. It should return success only after every element has passed. Returning the first accepted prefix under a success type would claim a complete result the implementation did not produce.

An index in an issue path tells the caller where a nested failure occurred. Preserve the element decoder’s field information and prefix it with the row position. Empty lists need an explicit policy too: this course accepts them as a complete empty result.

A list decoder stops at the first bad rowTypeScript
type Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      path: string;
    };

function texts(input: unknown): Result<readonly string[]> {
  if (!Array.isArray(input)) {
    return { ok: false, path: "list" };
  }

  const result: string[] = [];

  for (const [index, element] of input.entries()) {
    const item: unknown = element;

    if (typeof item !== "string") {
      return { ok: false, path: String(index) };
    }

    result.push(item);
  }

  return { ok: true, value: result };
}

const result = texts(["A", 25, "B"]);

console.log(result.ok ? result.value.join(",") : result.path);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
1

The accumulated A remains internal and is never returned as complete success after row 1 fails. Rebinding element to unknown avoids unchecked use of Array.isArray’s historical any[] narrowing.

Prefix a path without mutating the issueTypeScript
const fieldIssue = { path: "pages", message: "Expected integer" };
const row = 2;
const issue = { ...fieldIssue, path: `${row}.${fieldIssue.path}` };

console.log(issue.path);
console.log(fieldIssue.path);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
2.pages
pages

The wrapper enriches the path without mutating the nested decoder’s issue. That makes the same element decoder reusable inside different containers.

Try the rule on new inputs

Test an empty list, wrong outer container and invalid first, middle and last elements. Assert that no case returns a partial prefix as success. Keep the path policy consistent for every position.

Your turn

Exercise

Array Decoders: practice

Write the generic combinator arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]>, using the same Result, Decoder, at, count and field as the example. A non-array fails with an empty path and "Expected array"; a failing element fails with its index joined to the element's own path. Then uncomment the tests to print the five lines below. The fourth one composes your combinator with field, which neither of them knows about.

Text
1,2
1: Expected count
(root): Expected array
1.pages: Expected count
(empty)
Your workspaceTypeScript
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;

function at(prefix: string, path: string): string {
  return path === "" ? prefix : `${prefix}.${path}`;
}

const count: Decoder<number> = value =>
  typeof value === "number" && Number.isInteger(value) && value >= 0
    ? { ok: true, value }
    : { ok: false, issue: { path: "", message: "Expected count" } };

function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
  return value => {
    if (typeof value !== "object" || value === null) {
      return { ok: false, issue: { path: "", message: "Expected object" } };
    }
    const raw: unknown = Reflect.get(value, name);
    const result = decode(raw);
    if (result.ok) {
      return result;
    }
    return {
      ok: false,
      issue: { path: at(name, result.issue.path), message: result.issue.message }
    };
  };
}

// Write arrayOf here.

function show<T>(result: Result<readonly T[]>): string {
  if (result.ok) {
    return result.value.join(",") || "(empty)";
  }
  return `${result.issue.path || "(root)"}: ${result.issue.message}`;
}

// console.log(show(arrayOf(count)([1, 2])));
// console.log(show(arrayOf(count)([1, "x"])));
// console.log(show(arrayOf(count)("nope")));
// console.log(show(arrayOf(field("pages", count))([{ pages: 1 }, { pages: -2 }])));
// console.log(show(arrayOf(count)([])));

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

arrayOf has the same outer shape as field: it takes a decoder and returns a new arrow function value => .... Inside, it is the loop from the trace above, except that the element check is a call to decode rather than a typeof test.

Hint 2: a first step

Return the "Expected array" failure when Array.isArray is false. Then loop over value.entries() with an output array of type T[], binding each element to unknown before passing it to decode.

Show one solution
One possible solutionTypeScript
type Issue = { path: string; message: string };
type Result<T> = { ok: true; value: T } | { ok: false; issue: Issue };
type Decoder<T> = (value: unknown) => Result<T>;

function at(prefix: string, path: string): string {
  return path === "" ? prefix : `${prefix}.${path}`;
}

const count: Decoder<number> = value =>
  typeof value === "number" && Number.isInteger(value) && value >= 0
    ? { ok: true, value }
    : { ok: false, issue: { path: "", message: "Expected count" } };

function field<T>(name: string, decode: Decoder<T>): Decoder<T> {
  return value => {
    if (typeof value !== "object" || value === null) {
      return { ok: false, issue: { path: "", message: "Expected object" } };
    }
    const raw: unknown = Reflect.get(value, name);
    const result = decode(raw);
    if (result.ok) {
      return result;
    }
    return {
      ok: false,
      issue: { path: at(name, result.issue.path), message: result.issue.message }
    };
  };
}

function arrayOf<T>(decode: Decoder<T>): Decoder<readonly T[]> {
  return value => {
    if (!Array.isArray(value)) {
      return { ok: false, issue: { path: "", message: "Expected array" } };
    }
    const output: T[] = [];
    for (const [index, element] of value.entries()) {
      const item: unknown = element;
      const result = decode(item);
      if (!result.ok) {
        return {
          ok: false,
          issue: {
            path: at(String(index), result.issue.path),
            message: result.issue.message
          }
        };
      }
      output.push(result.value);
    }
    return { ok: true, value: output };
  };
}

function show<T>(result: Result<readonly T[]>): string {
  if (result.ok) {
    return result.value.join(",") || "(empty)";
  }
  return `${result.issue.path || "(root)"}: ${result.issue.message}`;
}

console.log(show(arrayOf(count)([1, 2])));
console.log(show(arrayOf(count)([1, "x"])));
console.log(show(arrayOf(count)("nope")));
console.log(show(arrayOf(field("pages", count))([{ pages: 1 }, { pages: -2 }])));
console.log(show(arrayOf(count)([])));

Enable JavaScript to edit and type-check this example.

Text
1,2
1: Expected count
(root): Expected array
1.pages: Expected count
(empty)

T flows from the element decoder to the result: arrayOf(count) is a Decoder<readonly number[]> because count is a Decoder<number>, and output.push(result.value) only type-checks after !result.ok has returned. That is all the checker can promise. It cannot tell whether you really called decode on every element or returned the partly-filled output on failure; those are runtime facts, shown by the "1: Expected count" line (no partial "1" success) and by the composed 1.pages path, which only appears if arrayOf keeps the inner path instead of replacing it.

Change it and test it

Test null, a bad first element and a bad last element. Then nest the combinators: what path does arrayOf(arrayOf(count))([[1], [2, -1]]) report? Explain how a dishonest element decoder would undermine the generic wrapper despite a correct type signature.

Was this article helpful?

Your response is saved on this device.