TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Do not throw

Model operations that could fail with a type, so that you can't forget to catch.

const couldFail = () => {
  throw new Error("Boom") // ⛔️ Oops, forgot to catch
}
type Result<Error, Value> =
  { _kind: "ok", value: Value } |
  { _kind: "error", value: Error }

  const couldFail = (): Result<string, number> => {
    return { _kind: "ok", value: 1 } // or
    return { _kind: "error", value: "no worries!" }
  } // ✅ You cannot forget to handle the error