Richard Michael Coo
Richard Michael Coo

Reputation: 120

How to augment a module from another "plugin" module in Typescript

If I type a module called "foo", like so:

declare module "foo" {
    interface App {
        bar: boolean;
    }

    namespace foo {}

    function foo(): App;

    export = foo;
}

How can I add a new property to the App interface when another module called foo-plugin is imported?

declare module "foo-plugin" {
    interface App {
        additional: string;
    }
}

I've tried the pattern described in https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-plugin-d-ts.html but it doesn't work, it only sees the bar property.

If I make the App interface top-level, the declarations are merged, but without the need to import foo-plugin.

This is what happens with chai-as-promised and sinon-chai. This code compiles but of course throws an exception, since eventually is undefined. Is it some sort of Typescript limitation and has to be accepted?

import { expect } from 'chai';

describe('Dummy', () => {
    it('passes', () => {
        expect('foo').to.eventually.equal(5);
    });
});

Thanks..

Upvotes: 4

Views: 4257

Answers (1)

BrunoLM
BrunoLM

Reputation: 100361

See here an example with axios

Basically on your plugin call it the same name as the module you want to extend

declare module "foo" { // foo-plugin
    interface App {
        additional: string;
    }
}

Declaration Merging on TypeScript docs

Upvotes: 5

Related Questions