Type-Safe Navigation with Next.js-Style Routes
What you'll learn: How to model file-based routing systems where filesystem paths become type-safe route strings using template literal types.
The File-Based Routing Mental Model
Modern frameworks like Next.js use your filesystem as your routing structure. A file at pages/blog/[id].tsx becomes the route /blog/123. Without TypeScript, navigating to these routes is just string manipulation—typos lead to broken links that only appear at runtime.
Template literal types let you model the entire routing structure as types, turning filesystem conventions into compile-time guarantees.
Building Route Types from File Structures
Imagine you have these files:
pages/index.tsx→/pages/about.tsx→/aboutpages/blog/[id].tsx→/blog/:idpages/user/[userId]/settings.tsx→/user/:userId/settings
You can represent all valid routes as a union of template literal types:
type StaticRoute = "/" | "/about";
type BlogRoute = `/blog/${string}`;
type UserRoute = `/user/${string}/settings`;
type AppRoute = StaticRoute | BlogRoute | UserRoute;
// Now your navigation function is type-safe
function navigate(path: AppRoute) {
// Implementation...
}
navigate("/about"); // ✓ Valid
navigate("/blog/123"); // ✓ Valid
navigate("/blog"); // ✗ Error: not assignable
navigate("/contct"); // ✗ Error: typo caught!
Extracting Dynamic Segments
You can combine template literals with infer to extract route parameters type-safely, ensuring navigation functions receive the right data for dynamic segments—but that's a pattern you'll explore as you continue building more sophisticated routing helpers.
Key Takeaway: Template literal types transform file-based routing conventions into type-safe route definitions, catching navigation errors at compile time instead of discovering broken links in production.