我是TypeScript的新手,我正在将现有项目迁移到它。在我的中间件函数(位于单独的文件上)上,有以下函数:
const checkCampgroundOwnership = async (
req: Request,
res: Response,
next: NextFunction
) => {
if (req.user && req.isAuthenticated()) {
try {
const foundCampground = await Campground.findById(req.params.id);
// does user own the campground?
if (foundCampground && foundCampground.author.id == req.user._id) {
next();
} else {
req.flash("error", "You don't have permission to do that");
res.redirect("back");
}
} catch (err) {
req.flash("error", "Campground not found");
return res.redirect("back");
}
} else {
req.flash("error", "You need to be logged in to do that");
return res.redirect("back");
}
};
在第11行上,当我检查是否有FoundCampground时,我在“ req.user._id”上遇到了此错误:Property '_id' does not exist on type 'User'
。
在我的server.ts上,我有这个:
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
我能做什么?
答案 0 :(得分:0)
我的解决方案:
declare namespace NodeJS {
export interface ProcessEnv {
MONGO_URI: string;
GOOGLE_API: string;
SECRET_KEY: string;
}
}
declare namespace Mytypes {
export interface User extends Express.User{
_id: string;
username: string;
isAdmin: boolean;
}
export interface ICustomRequest<T> extends Express.Request {
body: T;
params: {
id: string;
comment_id: string;
};
}
}