Suppose i want to extend String.prototype, so i have this in ext/string.ts for example:
interface String {
contains(sub: string): boolean;
}
String.prototype.contains = function (sub:string):boolean {
if (sub === "") {
return false;
}
return (this.indexOf(sub) !== -1);
};
When i do import * as string from 'ext/string.ts'
it fails with this error:
error TS2306: File 'ext/string.ts' is not a module
and this is supposed behavior , i didn't write export. But how do i tell to Typescript that i want to extend String.prototype then?
Suppose i want to extend String.prototype, so i have this in ext/string.ts for example:
interface String {
contains(sub: string): boolean;
}
String.prototype.contains = function (sub:string):boolean {
if (sub === "") {
return false;
}
return (this.indexOf(sub) !== -1);
};
When i do import * as string from 'ext/string.ts'
it fails with this error:
error TS2306: File 'ext/string.ts' is not a module
and this is supposed behavior , i didn't write export. But how do i tell to Typescript that i want to extend String.prototype then?
Share Improve this question edited May 3, 2016 at 12:54 Ahmed farag mostafa 2,9742 gold badges16 silver badges33 bronze badges asked May 3, 2016 at 12:33 layaboutlayabout 1991 silver badge15 bronze badges 1-
Honestly, you should really consider not extending the built-in types like this. When some future ES version es out with its own native implementation of
contains
your code will override that and possibly be slower than the native code. See stackoverflow./q/14034180/215552. – Heretic Monkey Commented May 3, 2016 at 14:05
1 Answer
Reset to default 12You just need to run the file without importing anything. You can do that with this code:
import "./ext/string";
However, if your string.ts
file contains any import statements then you will need to take out the interface and put it in a definition file (.d.ts
). You need to do this with external modules so that the piler knows it needs to be merged with the String
interface in the global scope. For example:
// customTypings/string.d.ts
interface String {
contains(sub: string): boolean;
}
// ext/string.ts
String.prototype.contains = function(sub:string): boolean {
if (sub === "") {
return false;
}
return (this.indexOf(sub) !== -1);
};
// main.ts
import "./ext/string";
"some string".contains("t"); // true
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744340607a4569380.html
评论列表(0条)