Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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..

like image 444
Richard Michael Coo Avatar asked Oct 27 '25 05:10

Richard Michael Coo


1 Answers

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

like image 148
BrunoLM Avatar answered Oct 29 '25 18:10

BrunoLM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!