typescript · level 3 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Wrap fetch once, and every request becomes safe.
Real apps ask servers for data. Gwecode answers requests to https://api.example.com with a practice server, so you can try this safely. Each address you can ask for is an . Replies can be missing, broken or the wrong shape, and json() gives any, which trusts everything.
A is a small function around another one that adds safety. getJson takes a URL and a type guard, checks the status and the data, and hands back a Result<T>. Every caller gets typed data or a clear error, never a surprise.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
async function getJson<T>(url: string, guard: (data: unknown) => data is T): Promise<Result<T>> {
const reply = await fetch(url);
if (!reply.ok) {
return { ok: false, error: `Server said ${reply.status}` };
}
const data: unknown = await reply.json();
if (!guard(data)) {
return { ok: false, error: "Unexpected data" };
}
return { ok: true, value: data };
}
const isText = (data: unknown): data is string => typeof data === "string";
getJson("https://api.example.com/motto", isText).then((result) => console.log(result)); .then takes a callback and runs it once the promise has its value.
guess first
The practice server sends back "42", in quotes. What comes back?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
async function getJson<T>(url: string, guard: (data: unknown) => data is T): Promise<Result<T>> {
const reply = await fetch(url);
if (!reply.ok) {
return { ok: false, error: `Server said ${reply.status}` };
}
const data: unknown = await reply.json();
if (!guard(data)) {
return { ok: false, error: "Unexpected data" };
}
return { ok: true, value: data };
}
const isNumber = (data: unknown): data is number => typeof data === "number";
getJson("https://api.example.com/score", isNumber).then((result) => console.log(result));
your turn
Your turn. Count the visitors.
Finish the guard so it accepts only numbers, then ask the practice server's visitors endpoint for the count.
fix it
The motto arrives, but the wrapper rejects it. Fix it.
- The practice server sends a perfectly good motto, yet the guard says no. What is
datareally holding? json()hands back a promise, not the data. A box of typeunknownaccepts anything, even a promise, so the checker cannot warn you.- On line 7, write
awaitbeforereply.json().
nailed it
you shipped a safe, typed way to fetch. :D
- A wrapper adds the checks once, so every caller is safe.
- Check the status, then the data, then return a
Result. unknownaccepts anything, so remember toawaitpromises.
new words in your collection
- endpoint
- wrapper
This lesson isn’t saved. A free account remembers every lesson you finish.