Track 04 · Lesson 13 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

Fail fast

Lesson 13 of 15· 6 min

Catch bad data as early as possible, and stop with an error that says exactly what's wrong.

Send a broken response

Pick a payload, send it, flip the switch

The API sends
[
  {
    "id": "a1",
    "name": "Tote bag",
    "price": "19.99"
  },
  {
    "id": "b2",
    "name": "Mug",
    "price": "19.99"
  }
]
  1. API response

    fetch("/api/cart")

  2. Boundary

    as CartItem[]

  3. Cart store

    useCart

  4. Cart total

    items.reduce()

  5. Checkout screen

    <CartTotal />

loadCart.tsWithout it
type CartItem = { id: string; name: string; price: number };

export async function loadCart() {
  const res = await fetch("/api/cart");
  // We tell TypeScript it's CartItem[]. Nobody actually checked.
  const items = (await res.json()) as CartItem[];
  useCart.setState({ items });
}

// …three components later, in CartTotal.tsx
const total = items.reduce((sum, i) => sum + i.price, 0);
// If price arrived as "19.99", this is string concatenation:
// 0 + "19.99" + "19.99" === "019.9919.99"

Why the bug traveled so far#

as CartItem[] doesn't check anything. It tells TypeScript "trust me", and TypeScript does. So the strings sailed through the store and the total calculation, where JavaScript happily joined "19.99" + "19.99" as text, and only a human looking at the checkout screen could tell something was wrong.

Check at the boundary#

Data from outside your code, like API responses, form input, URL parameters or local storage, should be checked the moment it enters. A schema library like Zod turns the check into one line: CartItem.array().parse(json). Bad data stops right there, with an error that names the exact field. Everything after the boundary can trust what it gets.

This is the same idea as Never trust the browser, pointed the other way: your server shouldn't trust clients, and your client shouldn't blindly trust APIs.

Check yourself

An API response is cast with as CartItem[]. What does that check at runtime?