Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add extension method to existing class

Tags:

typescript

I want to add method extension to existing class, but I don't know how. I tried this:

enter image description here

But I always receive Property 'addAssembler' doesnt exist on type 'Container' error.

like image 752
JaSHin Avatar asked Jan 03 '23 11:01

JaSHin


2 Answers

You can just just expant class members by defining interface with same name and adding new methods to it:

foo2.ts:

class Foo {
    spam?: string;
    bar() {
        console.log('Foo#bar');
    }
}

app.ts:

import { Foo } from './foo2';

declare module './foo2' {
    interface Foo {
        foo(): void;
    }
}

Foo.prototype.foo = function(this: Foo) {
    console.log('Foo#foo', this.spam);
}

const f = new Foo();
f.spam = 'eggs';
f.bar();
f.foo();
like image 188
Zbigniew Zagórski Avatar answered Jan 04 '23 23:01

Zbigniew Zagórski


You need to declare a module augmentation:

declare module 'inversify' {
    export interface Container {
        addAssembler(): void
    }
}

You can add the declaration above in your ts file where you add the method to the Container prototype.

Edit

Unfortunately the way Container is defined prevents augmentation. We can merge classes from modules with interfaces, but they have to be defined as export class Container {}. In this case container is exported as class Container {} export { Container }. This prevents augmentation unfortunately.

like image 22
Titian Cernicova-Dragomir Avatar answered Jan 05 '23 01:01

Titian Cernicova-Dragomir