跳到內容

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.config.ts 在你的 Next.js 設定中匯入類型。

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 only 套件不相容。

當使用 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 已在 TypeScript 4.9 中新增。我們建議升級到最新版本的 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 中啟用時,新增 遞增類型檢查 支援。