I am taking the example of FormControl but it could be applied to any constructor method within a module.
Let's say I would like to add the method myMethod(string): FormControl
to the existing FormControl class from ReactiveForm.
I thought I could do it this way:
import {FormControl} from '@angular/forms';
declare module '@angular/forms' {
interface FormControl {
myMethod(value: string): FormControl;
}
}
FormControl.prototype.myMethod = function(value) { /*TODO*/ };
const formControl = new FormControl('').myMethod('hello');
I would have worked with pure javacript, but I have several warnings and errors during typescript compilation:
Actualy, I think I understand both of the messages, but how can I do here? I have read the official type script documentation on it (https://www.typescriptlang.org/docs/handbook/declaration-merging.html) and cannot find a case that matchs mine...
Thanks a lot!
The FormControl
actually comes from another module within angular, that is the one you need to augment. I found that out by using go to definition command in Visual Studio Code. Also I took the liberty of adding a this
parameter to your augmentation function:
import {FormControl} from '@angular/forms';
declare module '@angular/forms/src/model' {
interface FormControl {
myMethod(value: string): FormControl;
}
}
FormControl.prototype.myMethod = function(this: FormControl, value: string) {
return this;
};
const formControl = new FormControl('').myMethod('hello');