TypeScript

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

要将 TypeScript 添加到现有项目,请将文件重命名为 .ts / .tsx。运行 next devnext build 会自动安装必要的依赖项,并添加带有推荐配置选项的 tsconfig.json 文件。

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

示例

类型检查 next.config.ts

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

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

const nextConfig: NextConfig = {
  /* 配置选项在这里 */
}

export default nextConfig

须知next.config.ts 中的模块解析目前仅限于 CommonJS。这可能会导致与 ESM 专用包在 next.config.ts 中加载时出现不兼容。

当使用 next.config.js 文件时,您可以使用 JSDoc 在 IDE 中添加一些类型检查,如下所示:

next.config.js
// @ts-check

/** @type {import('next').NextConfig} */
const nextConfig = {
  /* 配置选项在这里 */
}

module.exports = nextConfig

静态生成和服务端渲染

对于 getStaticPropsgetStaticPathsgetServerSideProps,您可以分别使用 GetStaticPropsGetStaticPathsGetServerSideProps 类型:

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 是在 TypeScript 4.9 中添加的。我们建议升级到最新版本的 TypeScript。

使用 API 路由

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

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,如下所示:

import type { AppProps } from 'next/app'

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

增量类型检查

v10.2.1 起,Next.js 支持在 tsconfig.json 中启用增量类型检查,这可以帮助加速大型应用程序中的类型检查。

在生产环境中禁用 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.1tsconfig.json 中启用时添加了增量类型检查 支持。

On this page