TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Parse, don't cast

APIs could return something that doesn't adhere to your expected response. It's always a good idea to parse values at the boundary of the system before they are sent in.

fetch(URL)
  .then(res => res.json())
  .then((user: User) => ...) // ⛔️
fetch(URL)
  .then(res => res.json())
  .then(json => parse(json)) // ✅
  .then(parsed => {
    if (parsed.success) {
      // Exactly what's expected
    } else {
      // Must handle bad response
    }
  })