跳到内容

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

您可以使用 TypeScript 并在您的 Next.js 配置中导入类型,方法是使用 next.config.ts

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  /* config options here */
}
 
export default nextConfig

须知next.config.ts 中的模块解析当前仅限于 CommonJS。这可能会导致 next.config.ts 中加载的仅 ESM 包不兼容。

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

next.config.js
// @ts-check
 
/** @type {import('next').NextConfig} */
const nextConfig = {
  /* config options here */
}
 
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 是在 4.9 版本中添加到 TypeScript 的。我们建议升级到最新版本的 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: {
    // !! WARN !!
    // Dangerously allow production builds to successfully complete even if
    // your project has type errors.
    // !! WARN !!
    ignoreBuildErrors: true,
  },
}
 
export default nextConfig

须知:您可以运行 tsc --noEmit 以在构建之前自行检查 TypeScript 错误。这对于 CI/CD 管道非常有用,您可以在部署之前检查 TypeScript 错误。

自定义类型声明

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

tsconfig.json
{
  "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 中启用时,添加了 增量类型检查 支持。