typescript 属性'role'在类型'User'上不存在|NextAuth中的适配器用户

z9smfwbn  于 2022-11-18  发布在  TypeScript
关注(0)|答案(1)|浏览(132)

我试图构建一个实现NextAuth的NextJS应用程序。在配置回调时,我在[...nextauth].ts中遇到以下错误:

Type error: Property 'role' does not exist on type 'User | AdapterUser'.
  Property 'role' does not exist on type 'User'.

  56 |     jwt: async ({ token, user }) => {
  57 |       // First time JWT callback is run, user object is available
> 58 |       if (user && user.id && user.role) {
     |                                   ^
  59 |         token.id = user.id;
  60 |         token.role = user.role;
  61 |       }

完整的回调代码部分如下所示:

callbacks: {
    jwt: async ({ token, user }) => {
      // First time JWT callback is run, user object is available
      if (user && user.id && user.role) {
        token.id = user.id;
        token.role = user.role;
      }
      return token;
    },
    session: async ({ session, token }) => {
      if (token && token.id && token.role) {
        session.id = token.id;
        session.role = token.role;
      }
      return session;
    },
  },

我使用的是带有电子邮件和密码的CredentialProvider。下面是authorize

async authorize(credentials) {
      if (!credentials || !credentials.email) return null;

      const dbCredentials = await executeAccountQuery(
        `SELECT password FROM auth WHERE email=?`,
        [credentials.email]
      );

      if (Array.isArray(dbCredentials) && "password" in dbCredentials[0]) {
        const isValid = await compare(
          credentials.password,
          dbCredentials[0].password
        );

        if (isValid) {
          return {
            id: "5",
            role: 99,
            name: "John Smith",
            email: credentials.email,
          };
        }
        return null;
      }
      return null; // login failed
    },

由于authorize函数的工作方式,我知道User对象将附加一个role(因为我已经测试过它),但我无法找到处理此错误并将其删除的方法。
类似地,我也收到session回调的错误,其中session.idsession.role也不存在于Session上。

qkf9rpyu

qkf9rpyu1#

经过大量的挖掘,通过互联网和一些试验和错误,我能够找出如何解决这个问题。
您将需要执行以下操作来手动扩展SessionUserJWT类型:
1.在根项目目录中创建types/next-auth.d.ts
1.将以下内容插入文件:

import { Session } from "next-auth";
import { JWT } from "next-auth/jwt";

declare module "next-auth" {
  interface Session {
    id: string;
    role: number;
  }

  interface User {
    id: string;
    role: number;
  }
}

declare module "next-auth/jwt" {
  interface JWT {
    id: string;
    role: number;
  }
}

1.运行npm run build并验证其生成是否正确。

相关问题