Next.js 16 类型安全:Async PageProps 与 Typed 路由
I’m happy to translate the article for you, but I’ll need the actual text of the post (the paragraphs, headings, etc.) in order to do so. Could you please paste the content you’d like translated? Once I have it, I’ll provide a Simplified‑Chinese version while keeping the source link, formatting, markdown, and code blocks unchanged.
Introduction
Next.js 已悄然成为最具类型安全性的全栈框架之一,但许多团队仅使用了它功能的一小部分。本文将介绍现代 App Router 中实用、可用于生产环境的类型安全特性,包括:
- TypeScript 检查器增强
- 静态类型链接
- 路由感知的类型助手
- 环境变量自动补全
- 类型化的
NextRequest与NextResponse
这不是入门指南;它侧重于在真实项目中防止 bug 的特性。
TypeScript 检查器
Next.js 附带了一个自定义的 TypeScript 插件,扩展了默认的 tsc 检查。它能够理解 Next.js 特有的概念,例如:
- 基于文件的路由
- 服务端组件 vs. 客户端组件
- 元数据 API
- 布局和页面约定
在 VS Code 中启用插件
- 打开命令面板(
Ctrl/Cmd + Shift + P)。 - 搜索 TypeScript: Select TypeScript Version。
- 选择 Use Workspace Version。
VS Code 现在会通过 next-env.d.ts 自动加载 Next.js 特定的类型规则,为元数据、缓存选项等 API 提供 IntelliSense 和上下文文档。
插件提供的额外检查
- 正确使用
"use client"指令。 - 防止在服务端组件中使用仅限客户端的 Hook(例如
useState)。 - 检测
page.tsx、layout.tsx和route.ts中的无效导出。
静态类型链接
Next.js 可以生成静态类型的路由,以消除拼写错误和无效导航。
启用类型化路由
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
typedRoutes: true,
};
export default nextConfig;
当 typedRoutes 启用后,Next.js 会在 .next/types 中创建路由定义。TypeScript 随后在编译时验证链接和导航,提供:
- 对无效路由的编译时错误
- 更安全的重构
- 仅建议有效路径的 IntelliSense
Source: …
路由感知助手
App Router 会在 next dev、next build 或通过 next typegen 时自动生成全局助手(无需导入)。
可用助手
PageProps– 页面组件的已类型化 propsLayoutProps– 布局组件的已类型化 propsRouteContext– API 路由的已类型化上下文
使用 PageProps
// pages/details/[slotId]/page.tsx
export default function Details({
params,
searchParams,
}: {
params: { slotId: string };
searchParams: { name?: string };
}) {
const { slotId } = params;
const { name } = searchParams;
return (
<>
Slot: {slotId}
<br />
Name: {name}
</>
);
}
更简洁且类型安全的写法:
export default async function Details(
props: PageProps
) {
const { slotId } = await props.params;
const { name } = await props.searchParams;
return (
<>
Slot: {slotId}
<br />
Name: {name}
</>
);
}
使用 LayoutProps
import type { ReactNode } from "react";
export default function RootLayout({
children,
}: {
children: ReactNode;
}) {
return (
<>
{children}
</>
);
}
已类型化的写法:
export default function RootLayout(
props: LayoutProps
) {
return (
<>
{props.children}
</>
);
}
在 API 路由中使用 RouteContext
import { NextRequest, NextResponse } from "next/server";
export async function GET(
_request: NextRequest,
ctx: RouteContext
) {
const { id } = await ctx.params;
return NextResponse.json({ msg: `Hello, ${id}!` });
}
RouteContext 为路由参数提供完整的 IntelliSense,省去手动键入类型的步骤。
已键入的 NextRequest 与 NextResponse
两个类在标准 Web API 的基础上扩展了 Next‑特有的辅助功能。
NextRequest
- 已键入的 cookie
- 通过
nextUrl解析的 URL - 适用于中间件的友好辅助函数
NextResponse
json()– 发送 JSON 响应redirect()– 执行重定向- Cookie 辅助函数
- 适用于 Edge 的 API
示例:
import { NextRequest, NextResponse } from "next/server";
export async function GET(_request: NextRequest) {
return NextResponse.json({ msg: "Hello!!!" });
}
结论
Next.js 类型安全不是关于编写更多类型;它是使用 TypeScript 作为防护栏,在不增加开销的情况下减少错误。通过启用内置的 TypeScript 插件、类型化路由和感知路由的辅助函数,你可以获得编译时保证以及在整个应用程序中更丰富的编辑器支持。