Type-Safe Link Components
What you'll learn: How to build React or framework link components that only accept valid route paths and automatically require the correct parameters as typed props.
The Link Component Challenge
Imagine you have a routing system with paths like /users/:userId and /posts/:postId/comments/:commentId. Traditional link components accept any string for the path and an untyped object for parameters — meaning you could accidentally write <Link to="/usrs/123" /> (typo!) or forget required parameters entirely.
With template literal types and route inference, you can build a <Link> component that only accepts valid paths from your routing configuration and forces you to provide correctly-typed parameters as props.
Building the Foundation
Start with your route definitions:
type Routes = {
"/": {},
"/about": {},
"/users/:userId": { userId: string },
"/posts/:postId/comments/:commentId": { postId: string, commentId: string }
}
Extract route parameter types from path strings:
type ExtractParams<Path extends string> =
Path extends `${infer _Start}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractParams<`/${Rest}`>]: string }
: Path extends `${infer _Start}:${infer Param}`
? { [K in Param]: string }
: {}
Type-Safe Link Component
Create a Link component that discriminates based on whether parameters are needed:
type LinkProps<Path extends keyof Routes> =
Routes[Path] extends Record<string, never>
? { to: Path } // No params required
: { to: Path, params: Routes[Path] } // Params required
function Link<Path extends keyof Routes>(props: LinkProps<Path>) {
// Implementation builds actual path from template + params
return props
}
// ✅ Valid: no params needed
Link({ to: "/" })
// ✅ Valid: params provided
Link({ to: "/users/:userId", params: { userId: "123" } })
// ❌ Error: params required but missing
// Link({ to: "/users/:userId" })
// ❌ Error: invalid route
// Link({ to: "/invalid" })
Why This Matters
This pattern prevents entire classes of routing bugs at compile time: typos in paths, missing parameters, wrong parameter names, and invalid route combinations. Your IDE provides autocomplete for both valid paths and their required parameters, making navigation code self-documenting and refactor-safe.
Key Takeaway: By combining template literal types with conditional props, you can build link components that enforce your entire routing schema at the type level, catching navigation errors before they reach users.