Capstone: a typed router
Relay needs a router for its HTTP endpoints: GET /hooks/:source/:id stores a webhook,
POST /jobs/:jobId/retry requeues a job. With a plain router every handler reads
req.params.sorce and finds out in production. Here the route string is the only place the param
names are written, and the compiler reads them from there.
This lesson builds the router as a chain: createRouter().get(path, handler).post(path, handler).
Each call changes the router’s type, so the handler gets the right params and the router knows
which routes it holds.
What the router does
Section titled “What the router does”get(pattern, handler)andpost(pattern, handler)each return a new router with the route added. The old router is not changed.- In a handler,
req.paramsisPathParams<typeof pattern>. For"/hooks/:source/:id"it is{ source: string; id: string }. router.routeslists the registered keys, such as"GET /hooks/:source/:id". Its element type is the union of exactly those strings.router.handle(method, path, body)runs the first route that matches. It returnsok(reply), orerr({ _tag: "NotFound", ... })when nothing matches. It never throws.
How the pieces fit
Section titled “How the pieces fit”- Lesson 1:
inferis how the params type reads the pattern. The router’sResultis the one from M3, and its error is a tagged value like the ones in M2. - Lesson 3:
PathParamsis a mapped type over the param names. - Lesson 4:
PathParamsitself, and the key type`GET ${P}`. The capstone starter gives youPathParamsandmatchRoutefrom that lesson, because the point here is how they plug into the router. - Lesson 7: a router is a chain of calls, each adding to the type. The type
parameter
Keysaccumulates withKeys | `GET ${P}`, the same way a variadic tuple grows.
The design
Section titled “The design”Two types carry the information. Router<Keys> records the route keys registered so far. Each
get<P extends string> takes the pattern as a type parameter P, so the handler is
(req: Request<P>) => Reply and the result is Router<Keys | `GET ${P}`>.
The runtime stores routes in one array, but routes have different P. Storing the handlers as they
are would need P to be the same in all of them. Instead each route becomes an Entry with a
run(path, body) function. run calls matchRoute(pattern, path) and the handler inside the
closure, where P is still known, and returns Reply | null. The array holds closures that only
mention strings.
interface Reply { readonly status: number readonly body: string}
interface Entry<Key extends string> { readonly key: Key readonly method: "GET" | "POST" readonly run: (path: string, body: string) => Reply | null}That is the same move as the overload in lesson 4: the typed promise stays outside, and the part that must handle many types at once sees only strings.
Exercise
Section titled “Exercise”The starter gives you Result, Reply, NotFound, PathParams and matchRoute. Its router has
only get, an untyped req.params, no routes and no post. Make Router generic over its keys,
type the handler’s params from the pattern and add the missing parts. The rules at the top give
the exact handle behavior.
Run it locally
Section titled “Run it locally”In the Relay project the router sits in front of the queue. Handlers use req.params with
no casts, and a misspelled param is rejected by the compiler:
interface Reply { readonly status: number readonly body: string}type Simplify<T> = { [K in keyof T]: T[K] } & {}type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : Ptype ParamName<S extends string> = S extends `:${infer Name}` ? Name : nevertype PathParams<P extends string> = Simplify<{ [K in ParamName<Segments<P>>]: string }>
declare function createRouter(): { get<P extends string>( pattern: P, handler: (req: { params: PathParams<P>; body: string }) => Reply, ): { handle(method: "GET" | "POST", path: string, body?: string): unknown }}
const router = createRouter().get("/hooks/:source/:id", (req) => ({ status: 200, body: `stored ${req.params.id} from ${req.params.source}`,}))
const result = router.handle("GET", "/hooks/github/42")Replace the declare with an import of your own createRouter. Bun’s fetch handler would call
router.handle(request.method, url.pathname) and turn the Result into a Response.
- The route string is the single source of truth:
PathParams<P>typesreq.params, and`GET ${P}`types the key. - A chain of calls changes the type step by step. Each method returns a new router with a bigger
Keysunion. - Closures hide the per-route type parameter, so one array can hold every route without a cast.
handlereturns aResultwith a taggedNotFound. An unknown path is a value, not an exception.- Computed types earn their place when a string is already the contract. Keep them to the one place where the strings are read.
Further reading
Section titled “Further reading”- Template Literal Types: unions in templates and the intrinsic string types.
- Mapped Types: the
asclause and modifiers. - Conditional Types:
inferand distribution.