LLearnCode
Academy/typescript/Contracts that survive contact with data

intermediate · 22 minute study

A type is a promise; a boundary needs evidence

An API, a save file and a restored backup can all disagree with your local types. Learn to turn uncertainty into a checked domain value.

Loading progressEvidence grows with practice
Useful preparation · 1 prerequisite

Use this as a map, not a lock. If these ideas are familiar, continue.

First, build a mental model

The compiler reasons about the evidence in your source. It cannot inspect tomorrow's network response. Treat external data as unknown, then narrow it with runtime checks.

  1. JSON.parse returns an unchecked value; deliberately assign it to unknown.
  2. Check object/null/array shape before reading fields.
  3. Validate domain rules as well as primitive types. A negative quantity is still a number.
  4. An assertion changes the compiler's belief without running a validator.
Read the codetypescript · educational example
type Order = { id: string; quantity: number };
function decodeOrder(value: unknown): Order | null {
  if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
  if (!('id' in value) || typeof value.id !== 'string') return null;
  if (!('quantity' in value) || typeof value.quantity !== 'number') return null;
  if (!Number.isInteger(value.quantity) || value.quantity < 1) return null;
  return { id: value.id, quantity: value.quantity };
}
const payload: unknown = { id: 'demo-1', quantity: -2 };
const order = decodeOrder(payload);
  1. Input

    payload is unknown: access is restricted until there is evidence.

  2. Narrow

    Each guard removes invalid possibilities from the branch that continues.

  3. Boundary

    The invalid quantity returns null. It never becomes a valid Order.

Production thinking

Take this beyond the example.

Keep transport decoding separate from authorization and transaction validation. Valid shape does not establish who may write the row or whether a concurrent write is safe.

Sources and further reading

Your evidence

unseen is a local learning signal, not a credential or proof of production competence.

Explain the mental model, then explicitly acknowledge it. Opening a page is not evidence.

Supported retries can complete this lesson. Independent evidence and delayed review determine the skill stage.

Next lesson · Follow the compiler through a branch →