×

typescript · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Return a result so callers cannot forget the failure.

Some calls fail: JSON.parse throws on broken text. runs the try block and, if anything throws, jumps to the catch block instead of crashing. The error it catches is unknown, because anything can be thrown, so check it before you use it.

A thrown error is invisible in a function's type, so callers forget it. A makes failure part of the return type: a discriminated union of { ok: true; value: T } and { ok: false; error: string }. Callers must check ok before they can reach the value.

type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseJson(text: string): Result<unknown> {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch {
    return { ok: false, error: `Not valid JSON: ${text}` };
  }
}
console.log(parseJson('{"cups": 2}'));
console.log(parseJson("{cups: 2}"));

If you do not need the error, write catch with no brackets after it.