Skip to content

Type-Safe Router

Medium ~50 min

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. 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 }.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

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

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic