F22*_*ing 3 mongoose node.js typescript passport.js passport-local-mongoose
我正在尝试使用 Passportjs 和 mongoose 进行身份验证,但我很难使用打字稿获得正确的类型。
Passport.use(UserModel.createStrategy())
Passport.serializeUser(UserModel.serializeUser()) // <---- Error
Run Code Online (Sandbox Code Playgroud)
我收到错误:
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.
Run Code Online (Sandbox Code Playgroud)
这就是我的 User 类的样子:
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)
Run Code Online (Sandbox Code Playgroud)
更新-我的 PR 已落地,因此该问题已在的v6.1.0@types/passport-local-mongoose中修复。要修复此问题,请将此依赖项更新为 6.1.0,然后Express.User从您自己的 mongo扩展该类User。因为您的 MongoUser使用与 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
Run Code Online (Sandbox Code Playgroud)
——原答案——
我相信这是我今天报告的@types/passport-local-mongoose 中的一个错误。您可以通过向此类添加强制转换来修复该错误。
Passport.use(UserModel.createStrategy())
Passport.serializeUser(UserModel.serializeUser() as any) // <---- No Error
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1107 次 |
| 最近记录: |