0

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?

1
  • I ran tsc (2.0.3 and 1.8.10) on a file containing only your code and it worked just fine. Are you sure that this is all? Commented Oct 4, 2016 at 23:10

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.