Passport-local-mongoose serializeUser 类型不正确

Passport-local-mongoose serializeUser incorrect type

我正在尝试使用 Passportjs 和 mongoose 进行身份验证,但我很难通过打字稿获得正确的类型。

Passport.use(UserModel.createStrategy())
Passport.serializeUser(UserModel.serializeUser()) // <---- Error

我收到错误:

No overload matches this call.
  Overload 1 of 2, '(fn: (user: User, done: (err: any, id?: any) => void) => void): void', gave the following error.
    Argument of type '(user: PassportLocalModel<User>, cb: (err: any, id?: any) => void) => void' is not assignable to parameter of type '(user: User, done: (err: any, id?: any) => void) => void'.
      Types of parameters 'user' and 'user' are incompatible.
        Type 'User' is missing the following properties from type 'PassportLocalModel<User>': authenticate, serializeUser, deserializeUser, register, and 68 more.
  Overload 2 of 2, '(fn: (req: IncomingMessage, user: User, done: (err: any, id?: unknown) => void) => void): void', gave the following error.
    Argument of type '(user: PassportLocalModel<User>, cb: (err: any, id?: any) => void) => void' is not assignable to parameter of type '(req: IncomingMessage, user: User, done: (err: any, id?: unknown) => void) => void'.
      Types of parameters 'user' and 'req' are incompatible.
        Type 'IncomingMessage' is missing the following properties from type 'PassportLocalModel<User>': authenticate, serializeUser, deserializeUser, register, and 53 more.

这是我的用户 class 的样子:


export interface User extends Document {
  email: String
  password: String
  displayName: String
}

const UserSchema = new Schema(
  {
    email: { type: String, unique: true },
    password: String,
    displayName: String,
  },
  { timestamps: true }
)

UserSchema.plugin(PassportLocalMongoose, {
  usernameField: 'email',
})

export const UserModel = model('User', UserSchema)

更新 - my PR landed so this has been fixed in v6.1.0@types/passport-local-mongoose。要获得修复,请将此依赖项更新到 6.1.0,然后从您自己的 mongo User 扩展 Express.User class。因为您的 Mongo User 使用与 Express User 相同的 class 名称,您需要创建一个别名,如下所示。在调用 Passport.serializeUser 之前执行此操作,您应该可以开始了。您可以将 Express.User 扩展名放在任何您想要的地方,我在 routes/user.ts 中添加了它,因为这是我的代码库中最合适的地方。

type _User = User;

declare global {
  namespace Express {
    interface User extends _User {
    }
  }
}

Passport.use(UserModel.createStrategy())
Passport.serializeUser(UserModel.serializeUser()) // <---- No Error

-- 原始答案 --

我认为这是@types/passport-local-mongoose 中的错误,我reported today。您可以通过像这样向任何对象添加强制转换来修复此错误。

Passport.use(UserModel.createStrategy())
Passport.serializeUser(UserModel.serializeUser() as any) // <---- No Error