Boss lesson · Unit 03
A Typed API Client
One route map drives the parameters and the result of every request
What you practise
- One route map drives the parameter and response types of
request(route, params) - A typo in a route or a field fails to compile
Try a question from this lesson
Pick one
The real route is /user; it takes { id } and returns { name }. This code has three typos. How many does the compiler catch?
declare function call(
route: string, params: any,
): Promise<any>;
const u = await call("/usr", { ID: 7 });
console.log(u.nmae);Correct answer
0
Why
None. The route is any string, the params are any and so is the result, so "/usr", ID and nmae all type-check. Each will surface in production instead. The fix: describe every route once, and derive all three types from that.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The route map
Write the API down once, as a type: each route maps to what it takes (in) and what it returns (out). This is the single source of truth.
Everything else is computed from it with tools you already have. keyof Api is the union of valid routes, and Api[R]["in"] is the parameter type of route R.
interface Api {
"/user": {
in: { id: number };
out: { name: string };
};
"/posts": {
in: { tag: string };
out: { n: number };
};
}
type Route = keyof Api;
// "/user" | "/posts"
type UserIn = Api["/user"]["in"];
// { id: number }Concept
How R is chosen
Why does one signature fit every route? At each call the compiler infers R from the first argument as a single literal: "/user", not string. A constraint made of string literals, like keyof Api, tells it to keep the literal.
With R pinned, Api[R]["in"] and Api[R]["out"] are ordinary lookups. The route string selects the types of everything else.
interface Api {
"/user": {
in: { id: number };
out: { name: string };
};
}
declare function req<R extends keyof Api>(
route: R, params: Api[R]["in"],
): Promise<Api[R]["out"]>;
req("/user", { id: 7 });
// R is "/user"
// params: { id: number }
// result: Promise<{ name: string }>10 more exercises in the app
- 5× multiple choice
- 2× fill the blanks
- 1× type the answer
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.