typescript · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Real apps fetch, check, and plan for the edge cases.
A real app joins everything up. It fetches data from the practice server, checks the status, reads the JSON as unknown, validates each item and then works with typed values. When something is wrong, it throws, and one catch explains the problem kindly.
Plan for each , an unusual situation that still happens: the address is wrong, the list is empty, or one item is broken. A good app copes with all of them without crashing.
async function main(): Promise<void> {
const reply = await fetch("https://api.example.com/names");
if (!reply.ok) throw new Error(`Server said ${reply.status}`);
const data: unknown = await reply.json();
if (!Array.isArray(data)) throw new Error("Expected a list");
const names = data.filter((item) => typeof item === "string");
console.log(`${names.length} good names:`, names);
}
main(); Test each edge case on purpose: a wrong address, an empty list, a broken item.
guess first
The server is having a bad day. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
async function main(): Promise<void> {
try {
const reply = await fetch("https://api.example.com/menu");
if (!reply.ok) throw new Error(`Menu is down (${reply.status})`);
console.log(await reply.text());
} catch (err) {
if (err instanceof Error) console.log(err.message);
}
}
main();
your turn
Your turn. Cope with an empty queue.
The practice server's queue is empty today. Fill in the length that means empty, and a friendly message to show instead. A return; with no value leaves main early.
fix it
A missing page gave a confusing message. Fix it!
- There is no crash, but the message is confusing. The server said 404, and the code tried to read Not found as JSON.
- Check
reply.okbefore reading the JSON, and throw a clear error that includesreply.status. - After line 3, add an
if (!reply.ok)that throws anew Errorwhose message holdsreply.status, then run.
nailed it
you built an app that copes with anything. :D
- Fetch, check the status, validate, then use typed data.
- Throw clear errors, and catch them in one place.
- Plan for edge cases: wrong addresses, empty lists, broken items.
new words in your collection
- edge case
This lesson isn’t saved. A free account remembers every lesson you finish.