AI Hints
Home›TypeScript Tutorial›Async and Outside Data
TypeScript · Lesson 80 of 120

Typing JSON

Data from outside.

⏱ 2 min read▶ Video at 1:02:18🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Data from an API arrives as JSON. TypeScript has no idea what's inside. In real code you'd call fetch. Our pretend shop API works the same way, returning unknown.

Typing JSON
From the video: Typing JSON
  • JSON from APIs
  • Type unknown
  • A pretend API

shop-api.ts

The pretend API keeps some JSON responses, and waits a moment, like a network would. Get returns unknown, honestly, because callers can't be sure what comes back.

shop-api.tstypescript
const DATA: Record<string, unknown> = {
  "/bikes": [{ model: "Trail 500", price: 849.5 }, { model: "Volt 7", price: 2199 }],
  "/orders/1042": { id: 1042, status: "shipped", total: 65 },
  "/orders/1043": { id: 1043, status: "packing", total: "thirty" },
};

export async function get(path: string): Promise<unknown> {
  await new Promise(resolve => setTimeout(resolve, 100));   // pretend network delay
  if (!(path in DATA)) throw new Error(`404 Not Found: ${path}`);
  return structuredClone(DATA[path]);
}

Trusting the data

We tell TypeScript the order matches our type, with as. It compiles. But order ten forty three's total is really text. Run it. Adding VAT produces nonsense, with no error at all.

app.tstypescript
import { get } from "./shop-api.js";

type Order = { id: number; status: string; total: number };

const order = (await get("/orders/1043")) as Order;
console.log("Total with VAT:", order.total * 1.2);
Output
Total with VAT: NaN
Also uses shop-api.ts
const DATA: Record<string, unknown> = {
  "/bikes": [{ model: "Trail 500", price: 849.5 }, { model: "Volt 7", price: 2199 }],
  "/orders/1042": { id: 1042, status: "shipped", total: 65 },
  "/orders/1043": { id: 1043, status: "packing", total: "thirty" },
};

export async function get(path: string): Promise<unknown> {
  await new Promise(resolve => setTimeout(resolve, 100));   // pretend network delay
  if (!(path in DATA)) throw new Error(`404 Not Found: ${path}`);
  return structuredClone(DATA[path]);
}

Summary

Data from outside is unknown. Asserting a type doesn't make it true. Next, errors in catch.

Key takeaways
  • unknown
  • as hides bugs
  • Validate instead
Next up: Errors in catch — unknown errors