This doesn't work
interface String {
contains(s:string):boolean;
}
String.prototype.contains=(s:string):boolean=>this.indexOf(s)!==-1;
because Property 'contains' does not exist on type 'String'
This is a bit of a surprise since adding it was the entire point of the interface declaration. http://www.typescriptlang.org/docs/handbook/declaration-merging.html suggests that the above code is legal. String
is in the global namespace as far as I can tell by examining lib.es2015.wellknown.d.ts
.
What's the right way to go about this? After reading Aluan Haddad's Extending third party module that is globally exposed I rewrote like this
declare global {
interface String {
contains(s: string): boolean;
}
}
String.prototype.contains=(s:string):boolean=>this.indexOf(s)!==-1;
and the interface change is now correct. But now 'this' implicitly has type 'any' because it does not have a type annotation.
Per further comments this
can be explicitly typed using function syntax.
String.prototype.contains = function (this: string, s:string):boolean {
return this.indexOf(s)!==-1;
};
It should also be noted that in the course of this investigation I discovered that contains
is implemented with the name includes
and is declared in lib.es2015.core.d.ts