gpt4 book ai didi

node.js - Passport-local-mongoose serializeUser 类型不正确

转载 作者:行者123 更新时间:2023-12-05 01:59:35 29 4
gpt4 key购买 nike

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

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.

这是我的用户类的样子:


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所以这已在 v6.1.0 中修复@types/passport-local-mongoose。要获得修复,请将此依赖项更新到 6.1.0,然后从您自己的 mongo User 扩展 Express.User 类。因为您的 Mongo User 使用与 Express User 相同的类名,您需要创建一个别名,如下所示。在调用 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

关于node.js - Passport-local-mongoose serializeUser 类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67726174/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com