为什么我不能在typescript中向String.prototype添加新方法

时间:2018-01-15 15:53:55

标签: javascript typescript

我想向String.prototype添加新方法。我试过这个。

interface String {
  newMethod(): void
}

String.prototype.newMethod = function() {}

typescriptlang.org playground没有错误。但仍然在我的本地计算机上显示错误Property 'newMethod' does not exist on type 'String'

我不知道为什么。

这是我的tsconfig.json

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

我安装了`@ types / node

我找到了一些例子。

// 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() {}

仅添加了import语句,发生错误。这么奇怪。我不知道为什么?

1 个答案:

答案 0 :(得分:2)

这就是我为" replaceAll"所做的。功能...

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;
};