TypeScript

Next.js 提供以 TypeScript 為優先的開發體驗,用於構建您的 React 應用程式。

它內建了對 TypeScript 的支持,可自動安裝必要的套件並配置適當的設定。

新專案

create-next-app 現在預設包含 TypeScript。

終端機
npx create-next-app@latest

現有專案

通過將檔案重新命名為 .ts / .tsx 來將 TypeScript 添加到您的專案中。執行 next devnext build 以自動安裝必要的依賴項並添加帶有推薦配置選項的 tsconfig.json 檔案。

如果您已經有 jsconfig.json 檔案,請將 paths 編譯器選項從舊的 jsconfig.json 複製到新的 tsconfig.json 檔案中,並刪除舊的 jsconfig.json 檔案。

最低 TypeScript 版本

強烈建議至少使用 TypeScript 的 v4.5.2 版本,以獲得諸如 導入名稱上的類型修飾符性能改進 等語法功能。

靜態生成和伺服器端渲染

對於 getStaticPropsgetStaticPathsgetServerSideProps,您可以分別使用 GetStaticPropsGetStaticPathsGetServerSideProps 類型:

pages/blog/[slug].tsx
import { 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 路由使用內建類型的示例:

import type { NextApiRequest, NextApiResponse } from 'next'

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

您還可以鍵入響應數據:

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

路徑別名和 baseUrl

Next.js 自動支持 tsconfig.json 中的 "paths""baseUrl" 選項。

您可以在 模組路徑別名文檔 上了解更多關於此功能的信息。

類型檢查 next.config.js

next.config.js 檔案必須是一個 JavaScript 檔案,因為它不會被 Babel 或 TypeScript 解析,但是您可以使用 JSDoc 在您的 IDE 中添加一些類型檢查,如下所示:

// @ts-check

/**
 * @type {import('next').NextConfig}
 **/
const nextConfig = {
  /* 配置選項在這裡 */
}

module.exports = nextConfig

增量類型檢查

v10.2.1 起,Next.js 支持在 tsconfig.json 中啟用 增量類型檢查,這可以幫助加快大型應用程式中的類型檢查速度。

忽略 TypeScript 錯誤

當您的專案中存在 TypeScript 錯誤時,Next.js 會使您的 生產構建 (next build) 失敗。

如果您希望 Next.js 即使在您的應用程式存在錯誤時也能危險地生成生產代碼,您可以禁用內建的類型檢查步驟。

如果禁用,請確保在構建或部署過程中運行類型檢查,否則這可能非常危險。

打開 next.config.js 並在 typescript 配置中啟用 ignoreBuildErrors 選項:

next.config.js
module.exports = {
  typescript: {
    // !! 警告 !!
    // 危險地允許生產構建即使您的專案有類型錯誤也能成功完成。
    // !! 警告 !!
    ignoreBuildErrors: true,
  },
}

版本變更

版本變更
v13.2.0靜態類型連結在 beta 版中可用。
v12.0.0SWC 現在預設用於編譯 TypeScript 和 TSX 以實現更快的構建。
v10.2.1當在您的 tsconfig.json 中啟用時,添加了 增量類型檢查 支持。

On this page