0

I am working on an express app and I wanted to add a new property on Request's class instance.

So I created a type.d.ts file at my project root similar to

type User = {
    name: string
}
declare namespace Express {
   export interface Request {
       user: User
   }
}

Then somewhere in my middleware function,

const user = req.user.name 

The above code throws error saying,

Property user does on exist on type Request<ParamsDictionary, any, any .....>

However, VS code does not complains anything about it, only when I try to start the express server using nodemon then it throws an error.

Any clue on this would be helpful. Thanks in advance.

laxman
  • 1,781
  • 4
  • 14
  • 32
  • Does this answer your question? [Extend Express Request object using Typescript](https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript) – Plagiatus Apr 19 '23 at 12:17
  • If you **right click > go to definition** does that take you to the proper type definition? Basically does VSCode see it as what you expect, or is it just not complaining because it doesn't know what it is? – Chris Barr Apr 19 '23 at 12:54

2 Answers2

0

This worked for me.

The first thing we need to do is to create a new declaration file @types > express > index.d.ts in the root of our project. You would notice this is the exact same file name and path in our node_modules/@types folder. For Typescript declaration merging to work, the file name and its path must match the original declaration file and path.

https://dev.to/kwabenberko/extend-express-s-request-object-with-typescript-declaration-merging-1nn5

laxman
  • 1,781
  • 4
  • 14
  • 32
0

I think you need to name your file index.d.ts. Also try modifying the code to this:

declare global {
  namespace Express {
    interface Request {
        user: User
    }
  }
}
export {};
Dang Ninh
  • 23
  • 6