Skip to main 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.

IDE 插件

¥IDE Plugin

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

¥Next.js includes a custom TypeScript plugin and type checker, which VSCode and other code editors can use for advanced type-checking and auto-completion.

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

¥You can enable the plugin in VS Code by:

  1. 打开命令面板(Ctrl/⌘ + Shift + P

    ¥Opening the command palette (Ctrl/⌘ + Shift + P)

  2. 搜索“TypeScript:选择 TypeScript 版本”

    ¥Searching for "TypeScript: Select TypeScript Version"

  3. 选择 "使用工作区版本"

    ¥Selecting "Use Workspace Version"

现在,在编辑文件时,将启用自定义插件。运行 next build 时,将使用自定义类型检查器。

¥Now, when editing files, the custom plugin will be enabled. When running next build, the custom type checker will be used.

TypeScript 插件可以帮助:

¥The TypeScript plugin can help with:

  • 如果传递了 段配置选项 的无效值,则会发出警告。

    ¥Warning if the invalid values for segment config options are passed.

  • 显示可用选项和上下文文档。

    ¥Showing available options and in-context documentation.

  • 确保正确使用 use client 指令。

    ¥Ensuring the use client directive is used correctly.

  • 确保客户端钩子(如 useState)仅在客户端组件中使用。

    ¥Ensuring client hooks (like useState) are only used in Client Components.

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

¥🎥 Watch: Learn about the built-in TypeScript plugin → YouTube (3 minutes)

端到端类型安全

¥End-to-End Type Safety

Next.js App Router 增强了类型安全性。这包括:

¥The Next.js App Router has enhanced type safety. This includes:

  1. 获取函数和页面之间没有数据序列化:你可以直接在服务器上的组件、布局和页面中进行 fetch。该数据不需要序列化(转换为字符串)即可传递到客户端以在 React 中使用。相反,由于 app 默认情况下使用服务器组件,因此我们可以使用 DateMapSet 等值,而无需任何额外的步骤。以前,你需要使用 Next.js 特定类型手动键入服务器和客户端之间的边界。

    ¥No serialization of data between fetching function and page: You can fetch directly in components, layouts, and pages on the server. This data does not need to be serialized (converted to a string) to be passed to the client side for consumption in React. Instead, since app uses Server Components by default, we can use values like Date, Map, Set, and more without any extra steps. Previously, you needed to manually type the boundary between server and client with Next.js-specific types.

  2. 简化组件之间的数据流:通过删除 _app 以支持根布局,现在可以更轻松地可视化组件和页面之间的数据流。以前,在各个 pages_app 之间流动的数据很难输入,并且可能会引入令人困惑的错误。有了 App Router 中的 并置数据获取,这不再是问题。

    ¥Streamlined data flow between components: With the removal of _app in favor of root layouts, it is now easier to visualize the data flow between components and pages. Previously, data flowing between individual pages and _app were difficult to type and could introduce confusing bugs. With colocated data fetching in the App Router, this is no longer an issue.

Next.js 中的数据获取 现在提供尽可能接近的端到端类型安全性,而无需对你的数据库或内容提供商选择做出规定。

¥Data Fetching in Next.js now provides as close to end-to-end type safety as possible without being prescriptive about your database or content provider selection.

我们能够像你期望的那样使用普通 TypeScript 输入响应数据。例如:

¥We're able to type the response data as you would expect with normal TypeScript. For example:

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 或类型安全的查询构建器来实现。

¥For complete end-to-end type safety, this also requires your database or content provider to support TypeScript. This could be through using an ORM or type-safe query builder.

示例

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

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:

// @ts-check

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

module.exports = nextConfig

¥Statically Typed Links

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

¥Next.js can statically type links to prevent typos and other errors when using next/link, improving type safety when navigating between pages.

要选择此功能,需要启用 experimental.typedRoutes 并且项目需要使用 TypeScript。

¥To opt-into this feature, experimental.typedRoutes need to be enabled and the project needs to be using TypeScript.

import type { NextConfig } from 'next'

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

export default nextConfig

Next.js 将在 .next/types 中生成一个链接定义,其中包含有关应用中所有现有路由的信息,然后 TypeScript 可以使用该信息在编辑器中提供有关无效链接的反馈。

¥Next.js will generate a link definition in .next/types that contains information about all existing routes in your application, which TypeScript can then use to provide feedback in your editor about invalid links.

目前,实验性支持包括任何字符串字面量,包括动态段。对于非字面量字符串,你当前需要手动将 href 转换为 as Route

¥Currently, experimental support includes any string literal, including dynamic segments. For non-literal strings, you currently need to manually cast the href with as Route:

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

// No TypeScript errors if href is a valid route
<Link href="/about" />
<Link href="/blog/nextjs" />
<Link href={`/blog/${slug}`} />
<Link href={('/blog' + slug) as Route} />

// TypeScript errors if href is not a valid route
<Link href="/aboot" />

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

¥To accept href in a custom component wrapping next/link, use a generic:

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

它是如何工作的?

¥How does it work?

运行 next devnext build 时,Next.js 会在 .next 内生成一个隐藏的 .d.ts 文件,其中包含有关应用中所有现有路由的信息(所有有效路由为 Linkhref 类型)。此 .d.ts 文件包含在 tsconfig.json 中,TypeScript 编译器将检查 .d.ts 并在编辑器中提供有关无效链接的反馈。

¥When running next dev or next build, Next.js generates a hidden .d.ts file inside .next that contains information about all existing routes in your application (all valid routes as the href type of Link). This .d.ts file is included in tsconfig.json and the TypeScript compiler will check that .d.ts and provide feedback in your editor about invalid links.

使用异步服务器组件

¥With Async Server Componens

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

¥To use an async Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher.

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

¥If you are using an older version of TypeScript, you may see a 'Promise<Element>' is not a valid JSX element type error. Updating to the latest version of TypeScript and @types/react should resolve this issue.

增量类型检查

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

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:

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

版本变更

¥Version Changes

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