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

自訂類型宣告

當您需要宣告自訂類型時,您可能會想修改 next-env.d.ts。然而,此檔案是自動生成的,因此您所做的任何更改都將被覆蓋。相反,您應該創建一個新檔案,例如 new-types.d.ts,並在您的 tsconfig.json 中引用它:

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

版本變更

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

On this page