NNext.js 中文网 GitHub

TypeScript

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

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

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

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

使用 TypeScript 7#

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

bash · pnpm
pnpm add -D typescript@^7
bash · npm
npm install -D typescript@^7
bash · yarn
yarn add -D typescript@^7
bash · bun
bun add -D typescript@^7

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

小知识:

  • CLI 类型检查会输出原生 tsc 的诊断信息。它不会应用 Next.js 特有的代码框,也不会针对路由、页面、layout 或 route handler 重写错误信息。
  • 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”

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

TypeScript 插件可以帮助你:

  • 当传入 segment 配置项的无效值时发出警告。
  • 显示可用选项和上下文相关文档。
  • 确保正确使用 'use client' 指令。
  • 确保客户端 hook(如 useState)仅在 Client Component 中使用。

🎥 观看: 了解内置 TypeScript 插件 → YouTube(3 分钟)

端到端类型安全#

Next.js App Router 具备更强的类型安全性。这包括:

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

Next.js 中的数据获取现在提供了尽可能接近端到端的类型安全,同时不会对你的数据库或内容提供商选择施加限制。

我们能够像普通 TypeScript 一样按你的预期为响应数据定义类型。例如:

app/page.tsx
async function getData() {
  const res = await fetch('https://api.example.com/...')
  // 返回值*不会*被序列化
  // 你可以返回 Date、Map、Set 等
  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.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  /* 在此处填写配置项 */
}

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.js
// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
  /* 在此处填写配置项 */
}

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 选择加入:

Terminal
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.mts
import type { NextConfig } from 'next'

// 支持顶层 await 和动态 import
const flags = await import('./flags.js').then((m) => m.default ?? m)

const nextConfig: NextConfig = {
  /* 在此处填写配置项 */
  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 属性。在 App Router 中,它还会为 next/navigation 的方法(如 push、replace 和 prefetch)提供类型。它不会为 Pages Router 中的 next/router 方法提供类型。

字面量 href 字符串会得到校验,而非字面量的 href 可能需要使用 as Route 进行类型转换。

要选择加入此功能,需要启用 typedRoutes,并且项目必须使用 TypeScript。

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

const nextConfig: NextConfig = {
  typedRoutes: true,
}

export default nextConfig

Next.js 会在 .next/types 中生成一个链接定义,其中包含应用中所有现有路由的信息,TypeScript 随后可利用这些信息在你的编辑器中对无效链接给出反馈。

小知识:如果你没有使用 create-next-app 来搭建项目,请确保通过将 .next/types/**/*.ts 添加到 tsconfig.json 的 include 数组中来包含生成的 Next.js 类型:

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

目前,支持范围包括任何字符串字面量(包括动态 segment)。对于非字面量字符串,你需要手动使用 as Route 进行类型转换。以下示例展示了 next/link 和 next/navigation 的用法:

app/example-client.tsx
'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 href="/about" />
      <Link href={`/blog/${slug}`} />
      <Link href={('/blog/' + slug) as Route} />
      
      <Link href="/aboot" />

      
      <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>

      
      <button onClick={() => router.push(('/blog/' + slug) as Route)}>
        Push Non-literal Blog
      </button>
    </>
  )
}

对于由 proxy 定义的重定向路由,情况同样如此:

proxy.ts
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.tsx
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,请使用泛型:

tsx
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.ts
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.tsx
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,并在你的编辑器中对无效链接给出反馈。

环境变量的类型智能提示#

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

要选择加入此功能,需要启用 experimental.typedEnv,并且项目必须使用 TypeScript。

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

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

export default nextConfig

小知识:类型是根据开发运行时加载的环境变量生成的,默认情况下不包含 .env.production* 文件中的变量。要包含特定于生产环境的变量,请使用 NODE_ENV=production 运行 next dev。

与异步 Server Component 一起使用#

要将 async Server Component 与 TypeScript 一起使用,请确保使用 TypeScript 5.1.3 或更高版本,以及 @types/react 18.2.8 或更高版本。

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

静态生成与服务端渲染#

对于 getStaticProps、getStaticPaths 和 getServerSideProps,你可以分别使用 GetStaticProps、GetStaticPaths 和 GetServerSideProps 类型:

pages/blog/[slug].tsx
import type { GetStaticProps, GetStaticPaths, GetServerSideProps } from 'next'

export const getStaticProps = (async (context) => {
  // ...
}) satisfies GetStaticProps

export const getStaticPaths = (async () => {
  // ...
}) satisfies GetStaticPaths

export const getServerSideProps = (async (context) => {
  // ...
}) satisfies GetServerSideProps

小知识: satisfies 是在 4.9 中添加到 TypeScript 的。我们建议升级到最新版本的 TypeScript。

与 API Routes 一起使用#

以下是如何使用 API Routes 内置类型的示例:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ name: 'John Doe' })
}

你还可以为响应数据定义类型:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

type Data = {
  name: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  res.status(200).json({ name: 'John Doe' })
}

与自定义 App 一起使用#

如果你有一个自定义 App,可以使用内置类型 AppProps,并将文件名改为 ./pages/_app.tsx,如下所示:

ts
import type { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}

增量类型检查#

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

自定义 tsconfig 路径#

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

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

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

export default nextConfig

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

next.config.ts
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

<details> <summary>为什么你可能为构建使用单独的 tsconfig</summary>

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

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

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

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

</details>

小知识:

  • IDE 通常读取 tsconfig.json 以获取诊断和智能提示,因此即使生产构建使用替代配置,你仍然可以看到 IDE 警告。如果你希望编辑器中的行为保持一致,请镜像关键选项。
  • 在开发环境中,仅监视 tsconfig.json 的更改。如果你通过 typescript.tsconfigPath 编辑了其他文件名,请重启开发服务器以使更改生效。
  • 所配置的文件会用于 next dev、next build 和 next typegen。

自定义 distDir#

Next.js 会更新你的 tsconfig.json,将生成的类型包含在 distDir 中。如果你更改了 distDir,可能需要手动从 include 中移除旧路径。

在生产环境中禁用 TypeScript 错误#

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

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

如果禁用了该步骤,请务必在构建或部署流程中运行类型检查,否则可能非常危险。

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

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

const nextConfig: NextConfig = {
  typescript: {
    // !! 警告 !!
    // 危险:即使项目存在类型错误,也允许生产构建成功完成。
    // !! 警告 !!
    ignoreBuildErrors: true,
  },
}

export default nextConfig

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

自定义类型声明#

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

tsconfig.json
{
  "compilerOptions": {
    "skipLibCheck": true
    //...已截断...
  },
  "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 中启用时,新增对增量类型检查的支持。
Next.js 中文网