×

typescript · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Servers send , and you choose the label for it.

Servers usually send data as JSON: text written like TypeScript objects and arrays, such as {"name": "Rex", "age": 3}. await reply.json() reads the body and turns it into real objects and arrays.

The checker cannot see what a server will send, so json() gives the type . An any value switches the checker off: anything goes, even mistakes. Give it a proper label straight away, like const pet: Pet = await reply.json();.

An async function that fetches a pet can promise one back: Promise<Pet>. But a label is a promise, not a proof. If the practice server sends something else, the label is wrong. Unit 7 shows how to check.

interface Pet { name: string; age: number }
async function getPet(id: number): Promise<Pet> {
  const reply = await fetch(`https://api.example.com/pets/${id}`);
  return await reply.json();
}
async function main(): Promise<void> {
  const pet = await getPet(1);
  console.log(`${pet.name} is ${pet.age}.`);
}
main();

Avoid writing any yourself. It hides the very mistakes the checker is there to catch.