3

I want to add a new method to String.prototype. I tried this.

interface String {
  newMethod(): void
}

String.prototype.newMethod = function() {}

No errors in typescriptlang.org playground. But still show me a error Property 'newMethod' does not exist on type 'String' in my local computer.

I don't know why.

Here is my tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
     "outDir": "./lib",
     "rootDir": "./src",
  }
}

I install `@types/node


I found some example.

// example1: no error
interface String {
  newMethod(): void
}

String.prototype.newMethod = function() {}

// example2: has error
import * as path from 'path'
interface String {
  newMethod(): void
}

String.prototype.newMethod = function() {}

Only import statement added, error occured. So strange. I don't know why?

4
  • where are you defining the typings? Commented Jan 15, 2018 at 15:55
  • 1
    please provid a minimal reproducible example Commented Jan 15, 2018 at 15:55
  • I am not sure if it can be done here, but I had similar question of "how to change external module interface": stackoverflow.com/questions/46276117/… Commented Jan 15, 2018 at 16:02
  • @DanielA.White I added examples Commented Jan 15, 2018 at 16:09

1 Answer 1

4

This is what I did for a "replaceAll" function...

export {};

declare global {
    // tslint:disable-next-line:interface-name
    interface String {
        replaceAll(searchFor: string, replaceWith: string): string;
    }
}

// I hate how the javascript replace function only replaces the first occurrence...
String.prototype.replaceAll = function(this: string, searchFor: string, replaceWith: string) {
    // tslint:disable-next-line:no-invalid-this
    var value = this;
    var index: number = value.indexOf(searchFor);

    while (index > -1) {
        value = value.replace(searchFor, replaceWith);
        index = value.indexOf(searchFor);
    }

    return value;
};
Sign up to request clarification or add additional context in comments.

1 Comment

And I also want to know why The example 2 has error? Just because has a import statement?

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.