truedrog truedrog - 7 months ago 53
Javascript Question

How to add file with extending prototype in Typescript

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 did not write export.
But how do i tell to ts that i want to extend String.prototype then?

Answer

You just need to run the file by doing:

import "./string";

However, if your string.ts file contains imports then you will need to put the definition in one file like so:

// string.ts
String.prototype.contains = function (sub:string):boolean {
    if (sub === "") {
        return false;
    }
    return (this.indexOf(sub) !== -1);
};

Then put the interface in its own definition file. 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;
}

Then run the file that adds a function to the string prototype by doing:

import "./string";