Merging Declaration with ES6 Style Modules

I would like to add a property, id , to the Express Request interface. Express has a specific type definition. I tried all kinds of interface instructions for merging, all of which lead to errors or do not work.

I get access to express typing using the import of ES6 style modules: import * as express from 'express';

I tried merging with the Request object in the Express namespace.

 declare module Express { export interface Request { id: number; } } 

It silently does nothing. I tried merging with the actual module instead of the namespace, following the instructions of the new 1.8 compiler that I am using:

 import { Request } from 'express'; declare module 'express' { interface Request { id: number; } } 

These errors are because Module augmentation cannot introduce new names in the top level scope.

When I open the actual express.d.ts file, it looks like module e { ... } containing all the interfaces inside declare module "express" { ... } , which contains the line export = e; . Maybe this is somehow a problem due to naming of the namespace?

How do you do it right?

+7
typescript
source share
4 answers

In versions of TypeScript prior to v1.8, this was not allowed.

Starting with version v.1.8, a module extension is available. The syntax is identical to ambient ads (as you showed in your question) - the only difference is that what you posted above should work now.

Extension module allows you to expand the global and module area.

To expand the global scope, you should use global as the three module names:

 declare global { interface Array<T> { popFromTop(): T; } } 
+1
source share

Apparently, a problem with the compiler causes this problem:

https://github.com/Microsoft/TypeScript/issues/6722

I hope this is resolved soon.

0
source share

I want to add my 2 cents here; so I would add the id property to Request

  • Determine where you want the .d.ts file; it will contain your custom types that are common to the whole project, which I usually call it index.d.ts You cannot import types from modules into this file (since this is the environment declaration file). In this example:

index.d.ts

 interface Identificable { id: number } 
  1. In your typescript file, import the request as usual and define a new type that applies to both Request and your type.

handler.ts

 import { Request, Response } from 'express' type IdentificableRequest = Request & Identificable function myHandler(req: IdentificableRequest, res: Response) { const id = req.id // fine const params = req.params // fine too ... } 
0
source share

My problem was that in package.json I had "typescript": "2.0.3" and on my system I installed version 2.3.3.

I uninstalled version 2.3.3 and installed version 2.0.3 and it worked.

0
source share

All Articles