Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot add a new method to String.prototype in typescript

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?

like image 510
XGHeaven Avatar asked Feb 25 '26 20:02

XGHeaven


1 Answers

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;
};
like image 196
ganders Avatar answered Feb 28 '26 10:02

ganders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!