Course contentsShow
← TypeScript
Lesson 858 of 1,79619. Template Literal TypesFree lesson

Path Autocomplete in Routing Libraries

Leverage template literal unions to provide IDE autocomplete for all valid routes in your application.

Path Autocomplete in Routing Libraries

What you'll learn: How to leverage template literal types to provide IDE autocomplete for all valid routes in your application, eliminating typos and hardcoded route strings.

The Problem with String-Based Routes

Traditional routing libraries accept route paths as plain strings. When navigating in your app, you might write navigate('/users/123/profile') or link('/prodcts/shoes') — and that typo in "products" won't be caught until runtime.

Template Literal Types to the Rescue

By combining template literal unions with your route definitions, you can create a type that represents every valid route your app supports. TypeScript will then autocomplete these routes and catch mistakes before your code runs.

The Pattern

First, define your route structure as an object type where keys represent route segments. Then, use recursive template literal types to generate unions of all possible complete paths:

type Routes = {
  users: {
    ':id': {
      profile: {}
      settings: {}
    }
  }
  products: {
    ':id': {}
  }
  about: {}
}

type BuildPaths<T> = {
  [K in keyof T]: K extends string
    ? T[K] extends Record<string, unknown>
      ? `/${K}` | `/${K}${BuildPaths<T[K]>}`
      : `/${K}`
    : never
}[keyof T]

type AppRoutes = BuildPaths<Routes>
// Result: "/users" | "/users/:id" | "/users/:id/profile" | 
//         "/users/:id/settings" | "/products" | "/products/:id" | "/about"

Now your navigate() function can accept only AppRoutes, giving you full autocomplete and type safety.

The Analogy

Think of it like having a GPS that only allows you to select from actual addresses in its database rather than typing freely — no more navigating to non-existent streets.

Key Takeaway: Template literal unions transform your route definitions into autocomplete-enabled types, making navigation type-safe and eliminating an entire class of routing bugs at compile time.