Open this lesson on a wider screen to play it. The narrated transcript and animated code need room to sit side by side.
← All lessons// Plain TypeScript: to return a failure without throwing, you hand-roll a result
// union. Every codebase reinvents this shape, and a plain throw would erase the
// failure from the signature entirely.
type Parsed =
| { ok: true; value: number }
| { ok: false; error: string };
const parse = (s: string): Parsed => {
const n = Number(s);
return Number.isNaN(n)
? { ok: false, error: `not a number: ${s}` }
: { ok: true, value: n };
};
const result = parse("oops");
// ^? Parsed
console.log(result.ok ? result.value : result.error); // not a number: oops