download

Why does res.json() as Invoice let bad API data slip in?

Frontend~7 minReviewed 3 Dec 2026Free · No sign-in

Question

A billing API sends amountCents as "5000" on one invoice and omits amountCents on another ({"id": "inv_2", "paid": false}). Your TypeScript build passes with zero errors. In production, the second row displays $NaN for tax, and "5000" + 1000 renders "50001000" as the total.

  1. Why did as Invoice fail to catch both payloads?
  2. Write parseInvoice(data: unknown) with runtime checks and a type predicate so bad JSON throws right away.
  3. How do you guard null, arrays, NaN, and Infinity?
"CODE · TYPESCRIPT"
type Invoice = { id: string; amountCents: number; paid: boolean };

async function loadTaxCents(res: { json(): Promise<unknown> }) {
  const inv = (await res.json()) as Invoice;
  return Math.round(inv.amountCents * 0.2);
}
Show hints (3)
  1. "COMPILE VERSUS RUNTIME"

    TypeScript removes type declarations and as Invoice before the browser runs JavaScript. Does as generate any if check?

  2. "START FROM UNKNOWN"

    Keep parsed JSON typed as unknown. Check typeof data === "object", data !== null, and !Array.isArray(data) before reading fields.

  3. "GUARD BAD NUMBERS"

    typeof NaN is "number", and global isFinite("5000") coerces strings. Use typeof x === "number" && Number.isFinite(x) inside a type predicate data is Invoice.

Show checked explanation

TypeScript erases as Invoice at compile time, so zero validation runs when res.json() resolves. Treat raw JSON as unknown where data enters your app, validate every required field at runtime with a type predicate or schema parser, and throw early on bad shapes.

"SOLUTION · TYPESCRIPT"
type Invoice = { id: string; amountCents: number; paid: boolean };

function isInvoice(data: unknown): data is Invoice {
  if (typeof data !== "object" || data === null || Array.isArray(data))
    return false;
  if (!("id" in data && "amountCents" in data && "paid" in data))
    return false;
  return (
    typeof data.id === "string" && data.id.length > 0 &&
    typeof data.amountCents === "number" &&
    Number.isFinite(data.amountCents) &&
    typeof data.paid === "boolean"
  );
}
function parseInvoice(data: unknown): Invoice {
  if (!isInvoice(data)) throw new Error("Invalid invoice payload");
  return data;
}
const ok = parseInvoice({ id: "inv_1", amountCents: 5000, paid: true });
console.log(ok.id, Math.round(ok.amountCents * 0.2));
"OUTPUT"
inv_1 1000

TypeScript starter and solution executed on Node.js v24.15.0 (native type-stripping, no tsc type-checker) and tested across valid, missing-field, string-number, null, array, NaN, and Infinity payloads via Python 3.12.10; static type-erasure and type-predicate rules checked against TypeScript 5 and MDN documentation. Checked by an editor other than the author.

Walkthrough

Type assertions (value as Invoice) only tell the compiler to trust you. After TypeScript emits JavaScript, const inv = await res.json(); runs with no checks at all. Response.json() returns Promise<any> in standard DOM types, so bad server data flows straight into UI math.

Payloadas Invoice starterparseInvoice(data)
{ id: "inv_1", amountCents: 5000, paid: true }tax 1000, total 6000returns Invoice, tax 1000
{ id: "inv_2", paid: false }undefined * 0.2 -> NaNthrows Invalid invoice payload
{ id: "inv_3", amountCents: "5000", paid: true }"5000" + 1000 -> "50001000"throws Invalid invoice payload
null or []TypeError or NaNthrows Invalid invoice payload

1. Start from unknown, not any. Assign const raw: unknown = await res.json();. TypeScript then refuses property access until you narrow raw with real runtime checks.

2. Guard object quirks and narrow with in. In JavaScript, typeof null is "object", and typeof [] is also "object". Checking typeof data === "object" && data !== null && !Array.isArray(data) followed by "id" in data narrows unlisted keys to unknown without any as cast.

3. Guard numeric edge cases. typeof NaN and typeof Infinity both return "number". Global isFinite("5000") coerces the string to 5000 and returns true. Number.isFinite(data.amountCents) rejects strings, undefined, NaN, and Infinity without coercion.

4. Narrow once at the API edge. Returning data is Invoice ties your runtime checks to the static Invoice type. Downstream UI code receives a real Invoice without repeating typeof checks everywhere. For large APIs, schema libraries like Zod or Valibot generate the same runtime checks and infer the TypeScript type from one definition.

Common mistakes

  • Writing (await res.json()) as Invoice and assuming TypeScript checks the server response at runtime.
  • Checking only typeof data === "object" without data !== null. Reading data.id on null throws a TypeError.
  • Using global isFinite(value) instead of Number.isFinite(value). Global isFinite("5000") returns true and lets string numbers slip through.
  • Writing a type predicate data is Invoice that only checks "id" in data. TypeScript trusts your predicate even if its body skips amountCents.

Follow-up questions

  • "If a schema library already checks the payload, do you still need manual type predicates?" Usually no. Libraries like Zod, Valibot, or Ajv parse unknown data, report exact field paths on failure, and infer the TypeScript type so your schema and type never drift apart. Hand-written predicates stay useful for tiny payloads with zero extra bundle size.
  • "Should you reject unknown extra fields from the server?" Usually no on frontend clients. Backends often add new optional fields before older browser tabs reload. Validate the fields your UI reads and ignore extra properties, unless strict rejection is required for a security check.
  • "What if your API helper checks res.ok before calling res.json()?" You need both checks. res.ok catches HTTP 4xx and 5xx error pages before JSON parsing fails. Runtime schema validation catches malformed or drifted 200 OK JSON payloads.

What a strong answer covers

Explains type erasure for as Invoice, starts from unknown, guards null, arrays, NaN, Infinity, and string coercion with Number.isFinite, and validates once where API data enters the app.

Open in interactive practice deck →

Original OfferVibe question. TypeScript Type Assertions · TypeScript Type Predicates · Response.json() (MDN) · Number.isFinite() (MDN).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.