Search code examples
node.jstypescriptexpressmiddleware

Declaration merging with custom interface with typescript


I am looking to add a user property to the express.Request type such that req.user would be of my custom type IUser. I read that declaration merging was the way to go so I created a custom.d.ts file

declare namespace Express {
     export interface Request {
         user?: IUser;
     }
}

Although typescript now allows me to use req.user, it get defined as type any. Importing IUser in my typings file did not help either as it only made it worse with typescript now not recognizing req.user at all. How can my typing be considered as IUser by the IDE?


Solution

  • First, don't extend the Express Request all the time as it's not the case all the time! You have to change the request interface only in specific routes.

    Secondly, don't use the optional field ? because it's not optional once it's approved (I guess)

    All you have to do it extend the Express Request with your additional field, and annotate it on your routes. like this:

    interface IMyReq extends Request {
      user: IUser;
    }
    
    app.post('/api/users-list', (req: IMyReq, res) => {
     // Look ma a request with an authenticated user!
    });