This doesn\'t work
interface String {
contains(s:string):boolean;
}
String.prototype.contains=(s:string):boolean=>this.indexOf(s)!==-1;
If you're defining the augmentation inside of a module, that is a file containing a top-level import
or export
then you need to use a declare global
block in order to augment the global scope. Otherwise, the interface that you declare will not be merged into the global array interface because it's local to the module like any other declaration would be. The declare global syntax is specifically to cover this use case.
Furthermore, when you define the actual method you can't use an arrow function if the method itself is defined in terms of this
because Arrow functions have a statically scope this
while a dynamic this
is needed for methods.
Putting it together
// this is a module
export {}
declare global {
interface String {
contains(other: string): boolean;
}
}
String.prototype.contains = function (other) {
return this.indexOf(other) and !== -1;
};
Note that whether the type being augmented is a class or an interface, the member needs to be declared in an interface as above because interfaces can merge with classes and interfaces can merge with interfaces but classes do not merge.