N Next.js 中文
原文 ↗

TypeScript

Next.js 为构建你的 React 应用提供 TypeScript 优先的开发体验。

更新于 2026-08-25Next.js 16.4.6

Next.js 内置了 TypeScript,当你使用 create-next-app 创建新项目时,会自动安装必要的包并配置合适的设置。

要向现有项目添加 TypeScript,请将某个文件重命名为 .ts / .tsx。运行 next dev 和 next build,即可自动安装必要的依赖,并添加一个包含推荐配置选项的 tsconfig.json 文件。

须知:

如果你已经有 jsconfig.json 文件,请将 paths 编译器选项从旧的 jsconfig.json 复制到新的 tsconfig.json 文件中,并删除旧的 jsconfig.json 文件。

使用 TypeScript 7

TypeScript 7 目前不提供 JavaScript 编译器 API。要在 next build 期间使用 TypeScript 7,请在你的项目中安装它:

pnpm

pnpm add -D typescript@^7

npm

npm install -D typescript@^7

yarn

yarn add -D typescript@^7

bun

bun add -D typescript@^7

Next.js 默认使用项目本地的 tsc CLI,因此无需额外配置。若要改用 JavaScript 编译器 API,请将 experimental.useTypeScriptCli 设置为 false。

须知:

  • CLI 类型检查会打印原生的 tsc 诊断信息。它不会应用 Next.js 特有的代码框,也不会为路由、页面、布局或路由处理器重写错误。
  • CLI 会检查由你的 tsconfig 文件所选的整个项目。这包括测试文件以及被该配置包含的 .next/dev/types。next build --debug-build-paths 不会缩小被类型检查的文件范围,并且与此选项一起使用时会生成警告。
  • typescript.tsconfigPath 仍会选择传递给 tsc 的配置。typescript.ignoreBuildErrors 会跳过类型检查步骤,包括 CLI 检查器。
  • experimental.useTypeScriptCli 是实验性的,其行为可能会发生变化。

IDE 插件

Next.js 包含一个自定义的 TypeScript 插件和类型检查器,VSCode 及其他代码编辑器可以使用它进行高级类型检查和自动补全。

你可以通过以下方式在 VS Code 中启用该插件:

  1. 打开命令面板(Ctrl/⌘ + Shift + P)
  2. 搜索 "TypeScript: Select TypeScript Version"
  3. 选择 "Use Workspace Version"

TypeScript 命令面板

现在,在编辑文件时,自定义插件将被启用。默认情况下,运行 next build 时会使用项目本地的 tsc CLI。将 experimental.useTypeScriptCli 设置为 false 以改用自定义类型检查器。

TypeScript 插件可以帮助完成以下工作:

  • 在传入了无效的 segment 配置选项值时发出警告。
  • 显示可用选项和上下文内文档。
  • 确保 'use client' 指令被正确使用。
  • 确保客户端 Hook(如 useState)仅在客户端组件中使用。

🎥 观看:

了解内置 TypeScript 插件 → YouTube(3 分钟)

端到端类型安全

Next.js App Router 具有增强的类型安全。这包括:

  1. 获取函数与页面之间无需序列化数据:你可以直接在服务器上的组件、布局和页面中使用 fetch。这些数据不需要被序列化(转换为字符串)后才能传递到客户端供 React 使用。相反,由于 app 默认使用服务器组件,我们可以直接使用 Date、Map、Set 等值,而无需任何额外步骤。以前,你需要使用 Next.js 特有的类型手动为服务器与客户端之间的边界标注类型。
  2. 组件之间更简洁的数据流:用根布局取代 _app 后,现在更容易可视化组件和页面之间的数据流。以前,在各个 pages 和 _app 之间流动的数据难以标注类型,并且可能引入令人困惑的 bug。借助 App Router 中的同位置数据获取,这不再是问题。

Next.js 中的数据获取现在在不对你的数据库或内容提供方选择做出规定的前提下,提供了尽可能接近端到端的类型安全。

我们可以像使用普通 TypeScript 那样,按你的预期为响应数据标注类型。例如:

app/page.tsxtsx
async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
  return res.json()
}

export default async function Page() {
  const name = await getData()

  return '...'
}

要实现完整的端到端类型安全,还需要你的数据库或内容提供方支持 TypeScript。这可以通过使用 ORM 或类型安全的查询构建器来实现。

路由感知类型辅助工具

Next.js 会为 App Router 的路由类型生成全局辅助工具。这些工具无需导入即可使用,并在 next dev、next build 期间或通过 next typegen 生成:

next-env.d.ts

Next.js 会在你的项目根目录生成一个 next-env.d.ts 文件。该文件引用了 Next.js 类型定义,使 TypeScript 能够识别非代码导入(图片、样式表等)以及 Next.js 特有的类型。

运行 next dev、next build 或 next typegen 会重新生成此文件。

须知:

  • next-env.d.ts 由 Next.js 管理。其内容属于实现细节,可能会随时间变化。请将其添加到 .gitignore 中。如果你的项目已经跟踪了该文件,请将其从 Git 中移除。不要手动编辑此文件。
  • 该文件必须位于你的 tsconfig.json include 数组中(create-next-app 会自动完成此操作)。

示例

对 Next.js 配置文件进行类型检查

你可以通过使用 next.config.ts 在 Next.js 配置中使用 TypeScript 并导入类型。

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  /* config options here */
}

export default nextConfig

目前,next.config.ts 中的模块解析仅限于 CommonJS。不过,在 Node.js v22.10.0 及更高版本中使用 Node.js 原生 TypeScript 解析器时,可以使用 ECMAScript Modules (ESM) 语法。

使用 next.config.js 文件时,可以像下面这样使用 JSDoc 在 IDE 中添加一些类型检查:

next.config.jsjs
// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
  /* config options here */
}

module.exports = nextConfig

为 next.config.ts 使用 Node.js 原生 TypeScript 解析器

注意:

仅在 Node.js v22.10.0+ 上且启用了该特性时可用。Next.js 不会启用它。

Next.js 通过 process.features.typescript 检测 Node.js 原生 TypeScript 解析器,该特性在 v22.10.0 中新增。当存在该解析器时,next.config.ts 可以使用原生 ESM,包括顶层 await 和动态 import()。此机制继承了 Node 解析器的能力和限制。

在 Node.js v22.18.0+ 版本中,process.features.typescript 默认启用。对于 v22.10.0 到 22.17.x 之间的版本,请使用 NODE_OPTIONS=--experimental-transform-types 选择启用:

Terminalbash
NODE_OPTIONS=--experimental-transform-types next <command>

适用于 CommonJS 项目(默认)

尽管 next.config.ts 在 CommonJS 项目中支持原生 ESM 语法,但 Node.js 默认仍会将 next.config.ts 视为 CommonJS 文件,导致 Node.js 在检测到模块语法时将文件重新解析为 ESM。因此,对于 CommonJS 项目,我们建议使用 next.config.mts 文件来明确表明它是 ESM 模块:

next.config.mtsts
import type { NextConfig } from 'next'

// Top-level await and dynamic import are supported
const flags = await import('./flags.js').then((m) => m.default ?? m)

const nextConfig: NextConfig = {
  /* config options here */
  typedRoutes: Boolean(flags?.typedRoutes),
}

export default nextConfig

适用于 ESM 项目

当在 package.json 中将 "type" 设置为 "module" 时,你的项目将使用 ESM。可在 Node.js 文档中详细了解此设置。在这种情况下,你可以直接使用 ESM 语法编写 next.config.ts。

须知:

在 package.json 中使用 "type": "module" 时,项目中的所有 .js 和 .ts 文件默认都会被视为 ESM 模块。如有需要,你可能需要将使用 CommonJS 语法的文件重命名为 .cjs 或 .cts 扩展名。

静态类型化链接

Next.js 可以对链接进行静态类型化,以便在使用 next/link 时防止拼写错误和其他错误,从而提高页面导航时的类型安全性。

在 Pages Router 和 App Router 中均适用于 next/link 的 href prop。在 App Router 中,它还会为 push、replace 和 prefetch 等 next/navigation 方法提供类型。它不会为 Pages Router 中的 next/router 方法提供类型。

字面量 href 字符串会被验证,而非字面量 href 可能需要使用 as Route 进行类型断言。

要选择启用此特性,需要启用 typedRoutes,且项目需要使用 TypeScript。

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  typedRoutes: true,
}

export default nextConfig

Next.js 会在 .next/types 中生成链接定义,其中包含应用程序中所有现有路由的信息,TypeScript 随后可以利用它在编辑器中就无效链接提供反馈。

须知:

如果你在没有 create-next-app 的情况下设置了项目,请通过在 tsconfig.json 的 include 数组中添加 .next/types/**/*.ts 来确保包含生成的 Next.js 类型:

tsconfig.jsonjson
{
  "include": [
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

目前,支持范围涵盖任何字符串字面量,包括动态段。对于非字面量字符串,你需要使用 as Route 手动进行类型断言。下面的示例展示了 next/link 和 next/navigation 两种用法:

app/example-client.tsxtsx
'use client'

import type { Route } from 'next'
import Link from 'next/link'
import { useRouter } from 'next/navigation'

export default function Example() {
  const router = useRouter()
  const slug = 'nextjs'

  return (
    <>
      {/* Link: literal and dynamic */}
      <Link href="/about" />
      <Link href={`/blog/${slug}`} />
      <Link href={('/blog/' + slug) as Route} />
      {/* TypeScript error if href is not a valid route */}
      <Link href="/aboot" />

      {/* Router: literal and dynamic strings are validated */}
      <button onClick={() => router.push('/about')}>Push About</button>
      <button onClick={() => router.replace(`/blog/${slug}`)}>
        Replace Blog
      </button>
      <button onClick={() => router.prefetch('/contact')}>
        Prefetch Contact
      </button>

      {/* For non-literal strings, cast to Route */}
      <button onClick={() => router.push(('/blog/' + slug) as Route)}>
        Push Non-literal Blog
      </button>
    </>
  )
}

同样适用于由 proxy 定义的重定向路由:

proxy.tsts
import { NextRequest, NextResponse } from 'next/server'

export function proxy(request: NextRequest) {
  if (request.nextUrl.pathname === '/proxy-redirect') {
    return NextResponse.redirect(new URL('/', request.url))
  }

  return NextResponse.next()
}
app/some/page.tsxtsx
import type { Route } from 'next'
import Link from 'next/link'

export default function Page() {
  return <Link href={'/proxy-redirect' as Route}>Link Text</Link>
}

要在包装 next/link 的自定义组件中接收 href,请使用泛型:

import type { Route } from 'next'
import Link from 'next/link'

function Card<T extends string>({ href }: { href: Route<T> | URL }) {
  return (
    <Link href={href}>
      <div>My Card</div>
    </Link>
  )
}

你也可以为简单的数据结构指定类型,并通过遍历来渲染链接:

components/nav-items.tsts
import type { Route } from 'next'

type NavItem<T extends string = string> = {
  href: T
  label: string
}

export const navItems: NavItem<Route>[] = [
  { href: '/', label: 'Home' },
  { href: '/about', label: 'About' },
  { href: '/blog', label: 'Blog' },
]

然后,遍历这些项以渲染 Link:

components/nav.tsxtsx
import Link from 'next/link'
import { navItems } from './nav-items'

export function Nav() {
  return (
    <nav>
      {navItems.map((item) => (
        <Link key={item.href} href={item.href}>
          {item.label}
        </Link>
      ))}
    </nav>
  )
}

它是如何工作的?

在运行时,next typegen、next dev 或 next build,Next.js 会在 .next 中生成一个隐藏的 .d.ts 文件,其中包含应用中所有现有路由的信息(所有有效路由作为 Link 的 href 类型)。这个 .d.ts 文件会被包含在 tsconfig.json 中,TypeScript 编译器将检查 .d.ts,并在你的编辑器中针对无效链接提供反馈。

环境变量的类型 IntelliSense

在开发过程中,Next.js 会在 .next/types 中生成一个 .d.ts 文件,其中包含已加载环境变量的信息,供编辑器的 IntelliSense 使用。如果同一个环境变量键在多个文件中定义,则会根据环境变量加载顺序进行去重。

要启用此功能,需要开启 experimental.typedEnv,并且项目需要使用 TypeScript。

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    typedEnv: true,
  },
}

export default nextConfig

须知:

类型是基于开发运行时加载的环境变量生成的,默认会排除 .env.production* 文件中的变量。要包含生产环境专用的变量,请使用 NODE_ENV=production 运行 next dev。

使用异步服务器组件

要将 async 服务器组件与 TypeScript 一起使用,请确保使用 TypeScript 5.1.3 或更高版本,以及 @types/react 18.2.8 或更高版本。

如果你使用的是较旧版本的 TypeScript,可能会看到 'Promise<Element>' is not a valid JSX element 类型错误。更新到最新版本的 TypeScript 和 @types/react 应能解决此问题。

增量类型检查

自 v10.2.1 起,Next.js 支持增量类型检查(需在你的 tsconfig.json 中启用),这有助于加快大型应用中的类型检查速度。

自定义 tsconfig 路径

在某些情况下,你可能希望为构建或工具链使用不同的 TypeScript 配置。为此,请在 next.config.ts 中设置 typescript.tsconfigPath,让 Next.js 指向另一个 tsconfig 文件。

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  typescript: {
    tsconfigPath: 'tsconfig.build.json',
  },
}

export default nextConfig

例如,为生产构建切换到不同的配置:

next.config.tsts
import type { NextConfig } from 'next'

const isProd = process.env.NODE_ENV === 'production'

const nextConfig: NextConfig = {
  typescript: {
    tsconfigPath: isProd ? 'tsconfig.build.json' : 'tsconfig.json',
  },
}

export default nextConfig

为什么你可能为构建使用单独的 tsconfig

在 monorepo 等场景中,你可能需要放宽检查——构建过程还会校验不符合项目标准的共享依赖;或者在 CI 中放宽检查,以便在本地迁移到更严格的 TypeScript 设置期间继续交付(同时仍希望 IDE 高亮显示误用)。

例如,如果你的项目使用 useUnknownInCatchVariables,但某些 monorepo 依赖仍假定使用 any:

tsconfig.build.jsonjson
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "useUnknownInCatchVariables": false
  }
}

这样可以通过 tsconfig.json 保持编辑器的严格检查,同时允许生产构建使用宽松的设置。

须知:

  • IDE 通常读取 tsconfig.json 来提供诊断和 IntelliSense,因此即使生产构建使用备用配置,你仍能看到 IDE 警告。如果希望在编辑器中保持一致,请同步关键选项。
  • 在开发环境中,只会监视 tsconfig.json 的更改。如果你通过 typescript.tsconfigPath 编辑了不同文件名的文件,请重启开发服务器以应用更改。
  • 配置的文件会用于 next dev、next build 和 next typegen。

在生产环境中禁用 TypeScript 错误

当你的项目中存在 TypeScript 错误时,Next.js 会让你的生产构建(next build)失败。

如果你希望 Next.js 在应用存在错误时仍危险地生成生产代码,可以禁用内置的类型检查步骤。

如果禁用,请确保在构建或部署流程中运行类型检查,否则这可能非常危险。

打开 next.config.ts,并在 typescript 配置中启用 ignoreBuildErrors 选项:

next.config.tsts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  typescript: {
    // !! WARN !!
    // Dangerously allow production builds to successfully complete even if
    // your project has type errors.
    // !! WARN !!
    ignoreBuildErrors: true,
  },
}

export default nextConfig

须知:

你可以在构建前自行运行 tsc --noEmit 检查 TypeScript 错误。这对于希望在部署前检查 TypeScript 错误的 CI/CD 流水线很有用。

自定义类型声明

当需要声明自定义类型时,你可能会想修改 next-env.d.ts。但是,此文件是自动生成的,因此你做的任何更改都会被覆盖。你应该改为创建一个新文件(我们称之为 new-types.d.ts),并在 tsconfig.json 中引用它:

tsconfig.jsonjson
{
  "compilerOptions": {
    "skipLibCheck": true
    //...truncated...
  },
  "include": [
    "new-types.d.ts",
    "next-env.d.ts",
    ".next/types/**/*.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": ["node_modules"]
}

版本变更

版本 变更
v15.0.0 为 TypeScript 项目新增了对 next.config.ts 的支持。
v13.2.0 静态类型链接处于 beta 阶段。
v12.0.0 现在默认使用 SWC 编译 TypeScript 和 TSX,以加快构建速度。
v10.2.1 在你的 tsconfig.json 中启用后,新增了对增量类型检查的支持。