Property 'id' does not exist on type 'User' with Passport and Typescript

Issue

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.

Solution

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.)

Answered By – Heiko Theißen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published