LLearnCode
Academy/typescript/Production TypeScript

advanced · 24 minute study

Make failure part of the API contract

Loading, unauthorized, invalid input and network failure should lead to deliberate behavior instead of undefined access and fake success.

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

A promise describes eventual completion. Its generic type describes the fulfilled value; TypeScript does not encode every possible rejection in Promise<T>. A result union can make expected failures explicit.

  1. Use a discriminated result for expected domain failures.
  2. Keep unexpected exceptions visible at an appropriate boundary.
  3. A catch value is unknown under strict checking; narrow before reading message.
  4. Cancellation and stale-result rejection are separate from validating a successful payload.
Read the codetypescript · educational example
type Result<T> = { ok: true; value: T } | { ok: false; error: 'network' | 'invalid' };
async function readScore(raw: string): Promise<Result<number>> {
  try {
    const value: unknown = JSON.parse(raw);
    return typeof value === 'number' && Number.isFinite(value)
      ? { ok: true, value } : { ok: false, error: 'invalid' };
  } catch { return { ok: false, error: 'invalid' }; }
}
async function show() {
  const result = await readScore('12');
  return result.ok ? result.value.toFixed(0) : result.error;
}
  1. Await

    The fulfilled value is still a union of expected outcomes.

  2. Discriminate

    ok=true establishes value; ok=false establishes error.

  3. Render

    The caller decides how each outcome appears to the learner/user.

Production thinking

Take this beyond the example.

Keep error codes stable and messages useful. Distinguish invalid input, authorization failure, conflict, transient failure and cancellation; retry only when the operation's semantics permit it.

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 · Design away impossible states →