2

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?

Ahmed farag mostafa
  • 2,802
  • 2
  • 14
  • 33
layabout
  • 189
  • 15
  • Honestly, you should really consider not extending the built-in types like this. When some future ES version comes out with its own native implementation of `contains` your code will override that and possibly be slower than the native code. See http://stackoverflow.com/q/14034180/215552. – Heretic Monkey May 03 '16 at 14:05

1 Answers1

12

You 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 compiler 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
David Sherret
  • 101,669
  • 28
  • 188
  • 178