Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a method to an existing class in typescript?

I am working in an angular 2 cli project in which I have to create a definition of a plugin, because it doesn't exists its typed. This plugin depends of a main library that has already its own typed and it works.

Anyway, I have two files the main one with

LIBRARY TYPES FILE A

export class A extends B {
    constructor(...);
    methodX(): void;
}

And I would need to add a new method for my plugin so my class would be like

export class A extends B {
        constructor(...);
        methodX(): void;
        methodY(): void;
    }

The point is that I need to add it in a separate file. The problem is adding a method to an existent class without creating a new one

If I put

PLUGIN TYPES FILE B

export class A extends B {
    constructor(...);
    methodX(): void;
}

or

PLUGIN TYPES FILE B

export class A extends B {
        constructor(...);
        methodX(): void;
        methodY(): void;
}

It doesn't work, does anyone how can I achieve overwriting a class or extending it with a new method that?

Thanks

like image 235
ackuser Avatar asked Mar 24 '17 12:03

ackuser


2 Answers

The "Declaration Merging > Module Augmentation" section from the TypeScript docs seems to offer the solution:

https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

In your case, if class A is exported from file1.ts, and you want to add methodY() to that class within a different module file2.ts, then try this:

//// file1.ts
export class A extends B {
    constructor(...);
    methodX(): void;
}

//// file2.ts
import { A } from "./file1";
declare module "./file1" {
    interface A {
        methodY(): void;
    }
}
A.prototype.methodY = function() {}
like image 112
Serban Stokker Avatar answered Oct 18 '22 19:10

Serban Stokker


You could do it by making an interface with the new method and modifying the prototype.

Something like this:

class B { }

class A extends B {
    constructor() {
        super();
    }
    methodX(): void { };
    methodY(): void { };
}


interface B {
    newMethod(): void;
}

B.prototype.newMethod = function () { console.log('a') };

This allows you do have proper typing when doing.

new A().newMethod();

I made a playground example here.

like image 20
toskv Avatar answered Oct 18 '22 19:10

toskv