TL;DR: Using NextJS's statically typed routes, how can I declare a type-safe array of arbitrary valid Route
s?
I have a NextJS project (v15, app router) project with typedRoutes
enabled. Suppose this is the file layout:
src/app/page.tsx
src/app/projects/page.tsx
src/app/projects/[projectId]/page.tsx
That means I can write code like this:
import Link from 'next/link';
function SomeValidLinks(){
const projectId = '123';
return [ // This all compiles because Next checks these are valid routes
<Link href='/'>Root</Link>,
<Link href='/projects'>Projects</Link>,
<Link href={`/projects/${encodeURIComponent(projectId)}`}>Project {projectId}</Link>,
];
}
function DoesNotWork(){
// Typecheck error: Type '"/banana"' is not assignable to type 'UrlObject | RouteImpl<"/banana">'.
return <Link href='/banana'>Invalid route</Link>;
}
This is very nice, but I can't figure out how to make an array of arbitrary, valid Route
values. Consider this code:
const routes: Route<string>[] = [];
routes.push('/'); // ✅
routes.push('/projects'); // ✅
routes.push(`/projects/${encodeURIComponent(projectId)}`); //