George Edwards George Edwards - 1 month ago 6
TypeScript Question

Prototype String with Typescript

The following prototype method for a JavaScript String in Typescript 2.0.3:

interface String {
splice(start: number, delCount: number, newSubStr: string): string;
}

String.prototype.splice = function(idx: number, rem: number, str: string): string {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};


throws the error:


error TS2339: Property 'splice' does not exist on type 'String'.


despite my interface. It seems to work fine in the playground. I am just running
tsc
on that file with no options. Why isn't this working?

Answer

It seems to work fine in the playground.

That because you probably have an import / export in your file. Fix:

declare global {
    interface String {
        splice(start: number, delCount: number, newSubStr: string): string;
    }
}

String.prototype.splice = function(idx: number, rem: number, str: string): string {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

More

This is covered here : https://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html#modifying-native-types

Comments