跳至內容
從 NextAuth.js v4 遷移嗎?請閱讀 我們的遷移指南.
開始使用TypeScript

TypeScript

Auth.js 致力於型別安全,因此它是以 TypeScript 編寫,並且 100% 型別安全。它帶有自己的型別定義,可在您的專案中使用。

即使您不使用 TypeScript,像 VS Code 這樣的 IDE 也會偵測到這一點,為您提供更好的開發人員體驗。在您輸入時,您會收到關於某些物件/函式外觀的建議,有時還會有文件、範例和其他有價值的資源的連結。

理念

我們選擇 模組擴充,而不是 泛型 作為主要技術,以便在您擴充 Auth.js 資源時,在您的應用程式中對它們進行型別檢查。

為什麼不使用 泛型

在子模組之間共用的介面不會作為泛型傳遞給 Auth.js 函式庫函式。

每當使用這些型別時,函式總是期望返回這些格式。使用泛型,人們可能可以在一個地方覆寫型別,但在另一個地方卻不行,這會導致型別與實作不同步。

使用模組擴充,您可以定義一次型別,並且可以確保它們在預期的位置始終相同。

模組擴充

Auth.js 函式庫帶有一些介面,這些介面在子模組和不同的 Auth.js 函式庫之間共用(例如:next-auth@auth/prisma-adapter 將依賴 @auth/core 的型別)。

此類介面的好例子是 SessionUser。您可以使用 TypeScript 的 模組擴充 來擴充這些型別,以在 Auth.js 中新增您自己的屬性,而無需在各處傳遞泛型。

讓我們來看一個擴充 Session 的例子。

auth.ts
import NextAuth, { type DefaultSession } from "next-auth"
 
declare module "next-auth" {
  /**
   * Returned by `auth`, `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: {
      /** The user's postal address. */
      address: string
      /**
       * By default, TypeScript merges new interface properties and overwrites existing ones.
       * In this case, the default session user properties will be overwritten,
       * with the new ones defined above. To keep the default session user properties,
       * you need to add them back into the newly declared interface.
       */
    } & DefaultSession["user"]
  }
}
 
export const { auth, handlers } = NextAuth({
  callbacks: {
    session({ session, token, user }) {
      // `session.user.address` is now a valid property, and will be type-checked
      // in places like `useSession().data.user` or `auth().user`
      return {
        ...session,
        user: {
          ...session.user,
          address: user.address,
        },
      }
    },
  },
})

模組擴充不限於特定的介面。您可以擴充我們定義的任何 interface,以下是一些您可能想要根據您的用例覆寫的更常見介面。

types.d.ts
declare module "next-auth" {
  /**
   * The shape of the user object returned in the OAuth providers' `profile` callback,
   * or the second parameter of the `session` callback, when using a database.
   */
  interface User {}
  /**
   * The shape of the account object returned in the OAuth providers' `account` callback,
   * Usually contains information about the provider being used, like OAuth tokens (`access_token`, etc).
   */
  interface Account {}
 
  /**
   * Returned by `useSession`, `auth`, contains information about the active session.
   */
  interface Session {}
}
 
// The `JWT` interface can be found in the `next-auth/jwt` submodule
import { JWT } from "next-auth/jwt"
 
declare module "next-auth/jwt" {
  /** Returned by the `jwt` callback and `auth`, when using JWT sessions */
  interface JWT {
    /** OpenID ID Token */
    idToken?: string
  }
}

模組宣告可以新增到專案的 tsconfig.json「包含」 的任何檔案。

資源

  1. TypeScript 文件:模組擴充
  2. DigitalOcean:TypeScript 中的模組擴充
  3. 建立資料庫適配器
Auth.js © Balázs Orbán 及團隊 -2024