Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration merging with ES6 style modules

Tags:

typescript

I'd like to add a property, id, to Express's Request interface. Express has a DefinitelyTyped type definition. I have tried all manner of specifying the interface for merging, all of which result in an error or do not work.

I'm accessing Express's typings using ES6 style module imports: import * as express from 'express';

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

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

This silently does nothing. I've tried merging with the actual module instead of the namespace, following the instructions of the new 1.8 compiler which I am using:

import { Request } from 'express';

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

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

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

How do you properly do this?

like image 453
David Pfeffer Avatar asked Jan 28 '16 14:01

David Pfeffer


Video Answer


1 Answers

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

From v1.8 onwards, module augmentation is available. The syntax is identical to ambient declarations (as you have shown in your question) - the only difference is that what you have posted above should work now.

Module augmentation allows you to extend global and module scope.

To extend the global scope, you would use global as three module name:

declare global {
    interface Array<T> {
        popFromTop(): T;
    }
}
like image 55
Fenton Avatar answered Sep 22 '22 18:09

Fenton