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



我想添加一个新方法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/节点


我找到了一些例子。

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

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

这就是我为"替换所有"函数所做的......

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

最新更新