AI Hints
TypeScript · Lesson 91 of 120

Result Types

Errors as values.

⏱ 2 min read▶ Video at 1:10:58🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Thrown errors are invisible in a function's type. A result type makes failure part of the return type. The caller must check for it, before using the value.

Result Types
From the video: Result Types
  • Throws are invisible
  • Failure in the type
  • Callers must check

A Result type

Result is either ok with a value, or not ok with an error. Parse quantity returns one. The caller checks ok, and only then can it use the value. Run it.

app.tstypescript
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parseQuantity(text: string): Result<number> {
  const n = Number(text);
  if (!Number.isInteger(n) || n < 1) return { ok: false, error: `"${text}" is not a valid quantity` };
  return { ok: true, value: n };
}

for (const input of ["3", "-2", "lots"]) {
  const r = parseQuantity(input);
  console.log(r.ok ? `Quantity ${r.value}` : `Problem: ${r.error}`);
}
Output
Quantity 3
Problem: "-2" is not a valid quantity
Problem: "lots" is not a valid quantity

Throw or return

Throw for bugs and truly unexpected problems. Return results for expected failures, like invalid input, or an item out of stock. Then the type tells callers what can go wrong.

keyvalue
Bugsthrow
Expected failuresResult
Callersmust check ok
Typedocuments failure

Summary

Result types put expected failures in the return type. Next, Node with TypeScript.

Key takeaways
  • Result<T>
  • ok: true | false
  • Must check
Next up: Node with TypeScript — files and paths