Skip to content

Decoder Contracts

The Course
•
25 min study

A type guard answers whether a value matches a shape; a decoder can return a normalized new value or a structured issue. type Decoder<T> = (value:unknown) => Result<T> expresses that reusable boundary.

Our decoder trims a title and validates a finite nonnegative integer page count. It does not coerce text counts, and it does not use assertions to pretend the input is valid. Constructing a new record also leaves unrelated input properties outside the domain value.

The compiler checks that a declared success has the required type. It does not prove your predicate conditions are complete or your normalization rule is correct. Test missing fields, null, wrong primitives, blank text, negative/fractional counts and zero.

Keep the result vocabulary from Day 3. A path identifies the failed field; a message explains its rule. These paths are simple human-readable field locations for this fixed schema, not a universal JSON-path query language.

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 Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      issue: {
        path: string;

        message: string;
      };
    };

type Decoder<T> = (value: unknown) => Result<T>;

const text: Decoder<string> = value => {
  if (typeof value !== "string" || value.trim() === "") {
    return {
      ok: false,
      issue: { path: "text", message: "Expected nonblank text" }
    };
  }

  return { ok: true, value: value.trim() };
};
const result = text(" Types ");

console.log(result.ok ? result.value : result.issue.message);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types

Read the compiler error

A success result promises a number, but no numeric evidence has been established.

Find and fix the type errorTypeScript
type Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      message: string;
    };

function decode(value: unknown): Result<number> {
  return { ok: true, value };
}

Enable JavaScript to edit and type-check this example.

Check your diagnosis

Narrow and validate value before constructing success. Casting would not implement the decoder.

A decoder returns evidence and a useful new value

A decoder can do more than answer whether the input is valid. It can normalize allowed text, construct a clean record and explain a failure. Keep that behavior separate from a type assertion, which performs no inspection or transformation.

A declared Decoder<T> is a promise made by the implementation. Runtime tests must challenge the conditions that support it. Include zero and empty input deliberately, because broad truthiness checks often reject valid data or accept invalid defaults.

Decode, then construct a new valueTypeScript
type Result<T> =
  | {
      ok: true;

      value: T;
    }
  | {
      ok: false;

      message: string;
    };

type Decoder<T> = (input: unknown) => Result<T>;

const text: Decoder<string> = input =>
  typeof input === "string" && input.trim() !== ""
    ? { ok: true, value: input.trim() }
    : { ok: false, message: "Blank or nontext" };
const result = text(" Types ");

console.log(result.ok ? result.value : result.message);
console.log(text(" ").ok);

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
Types
false

The accepted output differs from the padded input. Validation established the rule; projection returned the normalized value. Those are real runtime steps beyond declaring string.

A count guard on four inputsTypeScript
function validCount(input: unknown): input is number {
  return (
    typeof input === "number" &&
    Number.isFinite(input) &&
    Number.isInteger(input) &&
    input >= 0
  );
}

for (const input of [0, -1, 1.5, "0"]) {
  console.log(validCount(input));
}

Enable JavaScript to edit and type-check this example.

Check your prediction
Text
true
false
false
false

Each negative fixture targets a different rule. Number alone does not encode finite, integer or nonnegative, so the implementation needs all of them.

Try the rule on new inputs

Write a table mapping invalid container, missing field and invalid field value to a useful failure. Verify normalization and nonmutation for success rather than checking only the ok flag.

Debug a plausible mistake

Exercise

Repair the null boundary

Reject null before inspecting object properties. Print true then Read. Keep the argument unknown and return a newly projected valid value.

Use Check types to inspect the genuine diagnostic before repairing the code. Keep the intended contract; do not bypass the checker with any, a broad assertion or an ignore comment.

Find and fix the type errorTypeScript
function decode(value: unknown): { title: string } | null {
  if (typeof value !== "object" || !("title" in value)) {
    return null;
  }
  if (typeof value.title !== "string") {
    return null;
  }
  return { title: value.title.trim() };
}

console.log(decode(null) === null);
console.log(decode({ title: " Read " })?.title);

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

JavaScript reports typeof null as object, so that check alone is insufficient.

Hint 2: a first step

Guard null before using the in operator.

Show one solution
TypeScript
function decode(value: unknown): { title: string } | null {
  if (value === null || typeof value !== "object" || !("title" in value)) {
    return null;
  }
  if (typeof value.title !== "string") {
    return null;
  }
  return { title: value.title.trim() };
}

console.log(decode(null) === null);
console.log(decode({ title: " Read " })?.title);
Text
true
Read

typeof null is "object", so the original's first check let null through, and the checker said so: "title" in value was rejected because value was possibly null (TS18047). Testing value === null first leaves a non-null object, which in accepts. Running the original would have thrown on decode(null) instead of returning null; the true line is the evidence that it no longer does.

Your turn

Exercise

Decoder Contracts: practice

A decoder's output type can be narrower than any primitive. Write a Decoder<Status> where type Status = "draft" | "published". Any other value, including "Published" with a capital P, fails with path status and message Expected draft or published. Print published, then status: Expected draft or published for "Published".

Your workspaceTypeScript
// Define Result, Decoder and Status, then the status decoder and two calls.

Enable JavaScript to edit and type-check this example.

Hint 1: the idea

The checker narrows unknown with === comparisons against literals, just as it narrows with typeof. Ask which check gives it evidence for the union itself, not merely for string.

Hint 2: a first step

Start the arrow function with an if that compares value to each allowed literal, and return the success inside it.

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

type Decoder<T> = (value: unknown) => Result<T>;

type Status = "draft" | "published";

const status: Decoder<Status> = value => {
  if (value === "draft" || value === "published") {
    return { ok: true, value };
  }
  return {
    ok: false,
    issue: { path: "status", message: "Expected draft or published" }
  };
};

const a = status("published");
const b = status("Published");

console.log(a.ok ? a.value : a.issue.message);
console.log(b.ok ? "unexpected" : `${b.issue.path}: ${b.issue.message}`);

Enable JavaScript to edit and type-check this example.

Text
published
status: Expected draft or published

Comparing value === "draft" || value === "published" narrows unknown straight to the literal union, so { ok: true, value } is a Result<Status> with no assertion. A typeof string check would not be enough evidence: returning the value after it fails with TS2322, string is not assignable to Status. Whether "Published" should be accepted (case-insensitively) is a product rule the checker has no opinion on; the second line shows the rule this decoder chose.

Change it and test it

Add runtime assertions for negative, fractional, non-finite and missing values. Temporarily remove the integer check and verify a fractional test fails even though the decoder still type-checks.

Was this article helpful?

Your response is saved on this device.