A typed API client
Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.
What you will be able to do
#- Type request and response shapes.
- Validate untrusted responses at the boundary.
- Return typed errors instead of any.
Overview
#Define the contract
type User = { id: string; name: string };
A typed client
async function getUser(id: string): Promise<User> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as User;
}
The as User is an assertion: res.json() returns any. It is a claim, not a check.
Validating the boundary
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null &&
typeof (value as User).id === "string" && typeof (value as User).name === "string";
}
Call isUser after parsing and throw or return a Result when it fails.
Generic request helper
async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return parse(await res.json());
}
Passing the parser keeps the type honest: the caller proves the shape.
Errors as data
Returning a Result makes HTTP failures explicit and avoids throwing across layers.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Implement
Implement `request<T>(url: string, parse: (value: unknown) => T): Promise<T>` that throws on a non-ok response.
starter.typescriptexport async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> { // your code }Reveal the reference answer
reference.typescriptexport async function request<T>(url: string, parse: (value: unknown) => T): Promise<T> { const res = await fetch(url); if (!res.ok) throw new Error("HTTP " + res.status); return parse(await res.json()); }Authored expected output: Compiles with no errors. Runtime: a 200 response returns parse(json); a 500 throws.
The parser parameter proves the shape instead of asserting it.
Exercise 2Predict
Does `fetch` reject when the server returns HTTP 500?
Exercise 3Debug
This client trusts an untyped response. Add a guard so the type is real. ```ts async function getUser(id: string): Promise<User> { return (await fetch(`/api/users/${id}`)).json() as User; } ```
starter.typescriptasync function getUser(id: string): Promise<User> { return (await fetch(`/api/users/${id}`)).json() as User; }Reveal the reference answer
reference.typescriptasync function getUser(id: string): Promise<User> { const res = await fetch("/api/users/" + id); if (!res.ok) throw new Error("HTTP " + res.status); const data: unknown = await res.json(); if (!isUser(data)) throw new Error("invalid user payload"); return data; } function isUser(value: unknown): value is User { return ( typeof value === "object" && value !== null && typeof (value as User).id === "string" && typeof (value as User).name === "string" ); }Authored expected output: Compile-time unchanged; runtime now rejects a malformed body instead of returning it as User.
A guard turns the assertion into a real runtime check.
Common misconceptions
#- res.json() returns the declared type.
- as User validates the response.
- fetch rejects on HTTP 500.
Follow-up practice
#- typescript-type-level-challenges
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.