最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - How do I type an array of typed Routes? - Stack Overflow

programmeradmin6浏览0评论

TL;DR: Using NextJS's statically typed routes, how can I declare a type-safe array of arbitrary valid Routes?


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)}`); // 
发布评论

评论列表(0)

  1. 暂无评论