TypeScriptTips

Make bugs impossible.
One TypeScript tip at a time.

I like the tricks :) – Kasia

Fetch footgun

Prevent unsafe type casts by patching `json()` at the project level.

fetch(URL)
  .then(res => res.json())
  .then((user: User) => ...) // ⛔️
// global.d.ts

declare global {
  interface Body {
    json(): Promise<unknown>
  }
}

export {} // Needed to augment global scope

// index.ts

fetch(URL)
  .then(res => res.json())
  .then((user: User) => ...)
  // ✅ Does not compile:
  // Type 'unknown' is not assignable to type 'User'
  // ✅ You have to parse it.