Skip to main content

TypeScript

Next.js 为构建 React 应用提供了 TypeScript 优先的开发体验。

¥Next.js provides a TypeScript-first development experience for building your React application.

它具有内置的 TypeScript 支持,可以自动安装必要的包并配置正确的设置。

¥It comes with built-in TypeScript support for automatically installing the necessary packages and configuring the proper settings.

以及为你的编辑器准备的 TypeScript 插件

¥As well as a TypeScript Plugin for your editor.

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

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

新项目

¥New Projects

create-next-app 现在默认附带 TypeScript。

¥create-next-app now ships with TypeScript by default.

npx create-next-app@latest

现有项目

¥Existing Projects

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

¥Add TypeScript to your project by renaming 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 文件。

¥If you already had 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.

TypeScript 插件

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

插件功能

¥Plugin Features

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.

很高兴知道:未来将添加更多功能。

¥Good to know: More features will be added in the future.

最低 TypeScript 版本

¥Minimum TypeScript Version

强烈建议至少使用 TypeScript v4.5.2 才能获得 导入名称的类型修饰符性能改进 等语法功能。

¥It is highly recommended to be on at least v4.5.2 of TypeScript to get syntax features such as type modifiers on import names and performance improvements.

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

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
typedRoutes: true,
},
}

module.exports = 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.

端到端类型安全

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

异步服务器组件 TypeScript 错误

¥Async Server Component TypeScript Error

要将 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.

在服务器和客户端组件之间传递数据

¥Passing Data Between Server & Client Components

当通过 props 在服务器和客户端组件之间传递数据时,数据仍然被序列化(转换为字符串)以在浏览器中使用。然而,它不需要特殊的类型。它的类型与在组件之间传递任何其他属性相同。

¥When passing data between a Server and Client Component through props, the data is still serialized (converted to a string) for use in the browser. However, it does not need a special type. It’s typed the same as passing any other props between components.

此外,需要序列化的代码更少,因为未渲染的数据不会在服务器和客户端之间交叉(它保留在服务器上)。现在只有通过对服务器组件的支持才能实现这一点。

¥Further, there is less code to be serialized, as un-rendered data does not cross between the server and client (it remains on the server). This is only now possible through support for Server Components.

路径别名和 baseUrl

¥Path aliases and baseUrl

Next.js 自动支持 tsconfig.json "paths""baseUrl" 选项。

¥Next.js automatically supports the tsconfig.json "paths" and "baseUrl" options.

你可以在 模块路径别名文档 上了解有关此功能的更多信息。

¥You can learn more about this feature on the Module Path aliases documentation.

类型检查 next.config.js

¥Type checking next.config.js

next.config.js 文件必须是 JavaScript 文件,因为它不会被 Babel 或 TypeScript 解析,但是你可以使用 JSDoc 在 IDE 中添加一些类型检查,如下所示:

¥The next.config.js file must be a JavaScript file as it does not get parsed by Babel or TypeScript, however 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

增量类型检查

¥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 错误

¥Ignoring TypeScript Errors

当项目中存在 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.js 并在 typescript 配置中启用 ignoreBuildErrors 选项:

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

module.exports = {
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete even if
// your project has type errors.
// !! WARN !!
ignoreBuildErrors: true,
},
}

自定义类型声明

¥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

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