1

I'd like to extend Express' Request interface to include user information. This is common and has been asked here before, so I've been able to accomplish it with the following:

import { IHttpUser } from './user.interface';


declare module "express" {
    export interface Request{
        user?: IHttpUser;
    }
}

Great - that works. Without having to use any imports I can just go req.user wherever I am and I have typing information for it.

From what I understand using module is not the recommended way to do this. I should be using namespace. So I'd like to be able to go:

import { IHttpUser } from './user.interface';

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

...but I can't because if you have an import at the top this won't be picked up as being available globally (I apologize I don't know the correct terminology here).

So what is the "correct" way to do this? It works like I have it, but since I'm supposed to move to using namespace I'd like to learn that way.

WillyC
  • 3,917
  • 6
  • 35
  • 50
  • From where did you understand that "using module is not the recommended way to do this"? – Nitzan Tomer Dec 01 '16 at 22:39
  • https://www.typescriptlang.org/docs/handbook/namespaces.html near the top: "module X { is equivalent to the now-preferred namespace X {". If I can just go about my life happily using `module` then great, but then my question becomes - "what did MS mean when they stated the above?" – WillyC Dec 01 '16 at 22:40
  • But `express` is an external module and so based on this doc this is the right way. You just augment it. – Nitzan Tomer Dec 01 '16 at 22:42
  • OK - I had seen in the answers to other Stackoverflow questions people using the `namespace` keyword to extend express. For example, maximilianvp's answer here: http://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript/37379159#comment68962811_37379159 – WillyC Dec 01 '16 at 22:45
  • I'm not sure that there's an absolute "correct" way here. But, as I wrote, `express` is an external module, and so in my opinion even when augmenting it you should use the `module` keyword. – Nitzan Tomer Dec 01 '16 at 22:49

0 Answers0