Skip to content

TypeScript

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

¥Next.js comes with built-in TypeScript, automatically installing the necessary packages and configuring the proper settings when you create a new project with create-next-app.

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

¥To add TypeScript to an existing project, rename a file to .ts / .tsx. Run next dev and next build to automatically install the necessary dependencies and add a tsconfig.json file with the recommended config options.

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

¥Good to know: If you already have a jsconfig.json file, copy the paths compiler option from the old jsconfig.json into the new tsconfig.json file, and delete the old jsconfig.json file.

示例

¥Examples

类型检查 next.config.ts

¥Type checking next.config.ts

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

¥You can use TypeScript and import types in your Next.js configuration by using next.config.ts.

ts
import type { NextConfig } from 'next'

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

export default nextConfig

需要了解:next.config.ts 中的模块解析目前仅限于 CommonJS。这可能会导致与仅在 next.config.ts 中加载的 ESM 包不兼容。

¥Good to know: Module resolution in next.config.ts is currently limited to CommonJS. This may cause incompatibilities with ESM only packages being loaded in next.config.ts.

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

¥When using the next.config.js file, you can add some type checking in your IDE using JSDoc as below:

静态生成和服务端渲染

¥Static Generation and Server-side Rendering

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

¥For getStaticProps, getStaticPaths, and getServerSideProps, you can use the GetStaticProps, GetStaticPaths, and GetServerSideProps types respectively:

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

需要了解:satisfies4.9 中已添加到 TypeScript 中。我们建议升级到最新版本的 TypeScript。

¥Good to know: satisfies was added to TypeScript in 4.9. We recommend upgrading to the latest version of TypeScript.

使用 API 路由

¥With API Routes

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

¥The following is an example of how to use the built-in types for API routes:

ts
import type { NextApiRequest, NextApiResponse } from 'next'

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

你还可以输入响应数据:

¥You can also type the response data:

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

¥With custom App

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

¥If you have a custom App, you can use the built-in type AppProps and change file name to ./pages/_app.tsx like so:

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

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

增量类型检查

¥Incremental type checking

由于 v10.2.1 Next.js 在 tsconfig.json 中启用时支持 增量类型检查,因此这可以帮助加快大型应用中的类型检查速度。

¥Since v10.2.1 Next.js supports incremental type checking when enabled in your tsconfig.json, this can help speed up type checking in larger applications.

在生产中禁用 TypeScript 错误

¥Disabling TypeScript errors in production

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

¥Next.js fails your production build (next build) when TypeScript errors are present in your project.

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

¥If you'd like Next.js to dangerously produce production code even when your application has errors, you can disable the built-in type checking step.

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

¥If disabled, be sure you are running type checks as part of your build or deploy process, otherwise this can be very dangerous.

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

¥Open next.config.ts and enable the ignoreBuildErrors option in the typescript config:

ts
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 管道很有用。

¥Good to know: You can run tsc --noEmit to check for TypeScript errors yourself before building. This is useful for CI/CD pipelines where you'd like to check for TypeScript errors before deploying.

自定义类型声明

¥Custom type declarations

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

¥When you need to declare custom types, you might be tempted to modify next-env.d.ts. However, this file is automatically generated, so any changes you make will be overwritten. Instead, you should create a new file, let's call it new-types.d.ts, and reference it in your tsconfig.json:

版本变更

¥Version Changes

版本更改
v15.0.0为 TypeScript 项目添加了 next.config.ts 支持。
v13.2.0静态类型链接在测试版中可用。
v12.0.0现在默认使用 SWC 来编译 TypeScript 和 TSX 以加快构建速度。
v10.2.1tsconfig.json 中启用时添加 增量类型检查 支持。