![](/img/trans.png)
[英]TypeScript + Express + Passport.js - Property id does not exist on type User
[英]Property 'id' does not exist on type 'User' with Passport and Typescript
在 Express 中使用带有 Typescript 的 PassportJS,尝试访问req.user.id
时出现以下错误。
Property 'id' does not exist on type 'User'.ts(2339)
仅req.user
记录到控制台时,我可以清楚地看到有一个 id 属性,但是 Typescript 仍然抛出此错误。
这是我尝试运行的代码片段,
userRouter.post("/session", async (req: Request, res: Response) => {
const { startTime, endTime, desc } = req.body;
const { user } = req;
console.log(user!.id);
res.json({ message: "CREATE NEW SESSION" });
});
由于我是 TS 新手,因此我不确定解决此问题的步骤。 我的猜测是我必须在某处更改配置中的接口或其他内容。
PassportJS 没有声明User
界面的任何属性。 您可以通过将其与代码中的以下内容合并来扩展此定义:
declare global {
namespace Express {
interface User {
id: string
}
}
}
你的代码应该编译。
但是您希望user.id
在哪里填写? 您是否为此编写了自己的代码? 或者 PassportJS 是否填充了这个属性,尽管它没有声明它?
(奇怪的是,我能够通过将user..id
替换为user["id"]
来“欺骗” Typescript 编译器。)
我遇到了同样的错误,我解决了如下:
我制作了 IUser 界面:
import type { Document } from "mongoose"; interface IUser extends Document { name: string; email: string; hash: string; salt: string; isAdmin: boolean; } export default IUser;
我在用户 model 中使用它:
import { Schema, model } from "mongoose"; import IUser from "../types/User"; const userSchema = new Schema<IUser>( { name: { type: String, required: true, }, email: { type: String, required: true, unique: true, }, hash: { type: String, required: true, }, salt: { type: String, required: true, }, isAdmin: { type: Boolean, required: true, default: false, }, }, { timestamps: true, } ); const User = model("User", userSchema); export default User;
在用户 controller 我这样使用它:
import type { Request, Response } from "express"; import { genPassword } from "../utils/passwordUtils"; import User from "../models/userModel"; import IUser from "../types/User"; export const getUserProfile = async (req: Request, res: Response) => { const currentUser = req.user as IUser; try { const user = await User.findById(currentUser._id); if (user) { res.json({ success: true, user }); } else { res.status(404); throw new Error("User not found"); } } catch (error) { res.status(404); throw new Error("User not found"); } }; export const updateUserProfile = async (req: Request, res: Response) => { const currentUser = req.user as IUser; const user = await User.findById(currentUser._id); if (user) { user.name = req.body.name || user.name; user.email = req.body.email || user.email; if (req.body.password) { const saltHash = genPassword(req.body.password); const salt = saltHash.salt; const hash = saltHash.hash; user.hash = hash; user.salt = salt; } const updatedUser = await user.save(); res.json({ success: true, user: updatedUser }); } else { res.status(404); throw new Error("User not found"); } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.