Type-Safe Router
What you'll build
A router where route paths like '/users/:id' produce typed params { id: string }, and navigate() only accepts known routes.
Goals
- Use template literal types to parse route patterns
- Extract route params as a typed object
- Build a route map type from a routes definition
- Make navigate() type-check its route argument
Prerequisites
- Template literal types
- Conditional types (from project-11)
- Mapped types (from project-12)
Steps
- 1
Extract params from a route pattern
Write a type RouteParams<T> that extracts param names from a path like '/users/:id/posts/:postId' into { id: string; postId: string }. Use template literal inference. Acceptance: RouteParams<'/users/:id'> is { id: string }.
Hint
Use T extends
${string}:${infer Param}/${infer Rest}to peel off params recursively. - 2
Define a routes object
Create a routes object mapping route names to paths. The type of this object drives all downstream type safety. Acceptance: the routes object type-checks against a RouteMap interface.
Hint
e.g. const routes = { user: '/users/:id', post: '/posts/:id' } as const;
- 3
Type the navigate function
navigate should accept only known route names and a params object matching the route's params. Acceptance: navigate('user', { id: '123' }) compiles; navigate('user', {}) errors.
Hint
Use keyof typeof routes for the route name, and RouteParams<typeof routes[name]> for params.
- 4
Add query string types
Extend the router to accept typed query strings. Define a Query type per route and make navigate accept an optional query argument. Acceptance: navigate('post', { id: '1' }, { page: 2 }) type-checks.
Hint
Add a separate QueryMap<RouteName> type and intersect it into the navigate signature.
- 5
Build a useRoute hook
Write a hook (or function) that returns the current route and its typed params. Use the route map to narrow the return type. Acceptance: calling useRoute() on '/users/123' returns { name: 'user', params: { id: '123' } } with correct types.
Hint
This is the pattern behind type-safe routers like @tanstack/router and Remix's typed routes.
Try it yourself
What you learned
You built a type-safe router using template literal types — the same technique behind modern frameworks like @tanstack/router. Compile-time route safety catches a whole class of runtime errors.
Related Resources
Related Lessons
- Template Literal Types
Parse route patterns at the type level.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.