typescript · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A list of pets from the server. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Pet { name: string; age: number }
async function main(): Promise<void> {
const reply = await fetch("https://api.example.com/pets");
const pets: Pet[] = await reply.json();
const names = pets.map((pet) => pet.name);
console.log(pets.length, names);
}
main();
your turn
Your turn. Label the film reply.
The practice server sends a film like {"title": "Up", "minutes": 96}. Fill in the two property types, then label the reply with the interface.
fix it
any let a typo sneak through. Fix it!
- This crashes with a
TypeErrorwhile running. The checker said nothing, becausepethas the typeany. - Give
peta proper label, aPetinterface, and the checker will point straight at the typo. - Add
interface Pet { name: string; age: number }at the top, labelpet: Pet, and changenmaetoname.
nailed it
your server replies have labels now. :D
- Servers send JSON, and
reply.json()turns it into objects. json()givesany, which switches the checker off.- Label replies with an interface, but a label is not a proof.
new words in your collection
- JSON
- any
This lesson isn’t saved. A free account remembers every lesson you finish.