![](/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.