使用 Typescript 时如何更新 Next-auth 中会话回调中的会话类型

Vik*_*hat 12 authentication typescript next.js next-auth

我正在使用打字稿,我的 [...next-auth].tsx 文件如下所示:

import NextAuth, { Awaitable, Session, User } from "next-auth";
// import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

type ExtendedUserType = User & { username?: string; uid?: string };

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
    // ...add more providers here
  ],
  pages: {
    signIn: "/auth/signin", // for custom sign in page
  },
  callbacks: {
    async session({ session, token, user }): Awaitable<Session> {
      (session.user as ExtendedUserType).username = session.user?.name
        ?.split(" ")
        .join("")
        .toLocaleLowerCase();

      (session.user as ExtendedUserType).uid = token.sub;

      return session;
    },
  },
});


Run Code Online (Sandbox Code Playgroud)

使用钩子获取会话时,useSession我没有获得新添加的键的 Typescript 自动完成功能 - 'username'、'uid'

在此输入图像描述

我还收到此Awaitable<Session>类型 的打字稿错误在此输入图像描述

Vik*_*hat 29

上述问题的答案在这里讨论

太长了;next-auth.js.org/getting-started/typescript#module-augmentation

解决方案:

types/**/*.ts在 中添加以下内容tsconfig.json

{ 
  .
  .
  .
  "include": ["next-env.d.ts", "types/**/*.ts", "**/*.ts", "**/*.tsx"],
  .
  .
  .
}
Run Code Online (Sandbox Code Playgroud)

然后添加以下内容session.user

类型/next-auth.d.ts

import NextAuth from "next-auth"

declare module "next-auth" {
  /**
   * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
   */
  interface Session {
    user: {
      /** The user's name. */
      name: string
    }
  }
}
Run Code Online (Sandbox Code Playgroud)