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
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() {}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With