3

I’ve a custom type definition to augment an existing interface (Express Request as shown here). Content of express.d.ts:

declare namespace Express {
  export interface Request {
    name: string
  }
}

Works fine. But instead of name being a string, I need it to be a custom class MyClass now. The class definition looks like:

export class MyClass {
  first: string;
  last: string;
}

I change the interface augmentation to:

import { MyClass } from "../routes/myClass";
declare namespace Express {
  export interface Request {
    name: MyClass
  }
}

Now I get the following error when accessing req.name:

error TS2339: Property 'name' does not exist on type 'Request'.

I’ve found out, that my express.d.ts effectively becomes a “module” due to the added import statement. Still, its not clear to me how I could overcome my problem.

qqilihq
  • 10,794
  • 7
  • 48
  • 89
  • 1
    When you have a top level import/export statement, the file is an module file and you are not augmenting the global namespace Express anymore – unional Dec 26 '17 at 11:55

1 Answers1

5

As @unional mentioned in the comment, once you have top-level import or export in a file, top-level scope in a file becomes a module scope, separate from global scope.

To amend global declaration in a module, you have to use declare global to refer to Express in global namespace:

import { MyClass } from "../routes/myClass";
declare global {
  namespace Express {
    export interface Request {
      name: MyClass
    }
  }
}
artem
  • 46,476
  • 8
  • 74
  • 78