Using PassportJS in Express with Typescript, I get the following error when trying to access req.user.id
.
Property 'id' does not exist on type 'User'.ts(2339)
When logging just req.user
to the console, I can clearly see that there is an id property, however Typescript is throwing this error none the less.
Here is a snippet of the code I'm trying to run,
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" });
});
As I am new with TS, I am unsure of the steps to take in resolving this problem. My guess is I have to change an interface or something in the configuration somewhere.
PassportJS does not declare any properties of the User
interface. You can extend this definition by merging it with the following in your code:
declare global {
namespace Express {
interface User {
id: string
}
}
}
and your code should compile.
But where do you expect the user.id
to be filled? Have you written your own code for that? Or does PassportJS fill this property although it does not declare it?
(I was able to "fool" the Typescript compiler by replacing user!.id
with user["id"]
, perhaps because I did not use the --strict
option.)