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

Javascript 为什么我不能向typescript中的String.prototype添加新方法,javascript,typescript,Javascript,Typescript,我想向String.prototype添加一个新方法。我试过这个 interface String { newMethod(): void } String.prototype.newMethod = function() {} typescriptlang.org中没有错误。但是仍然向我显示一个错误,本地计算机中的类型“String”上不存在属性“newMethod” 我不知道为什么 这是我的tsconfig.json { "compilerOptions": { "tar

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

interface String {
  newMethod(): void
}

String.prototype.newMethod = function() {}
typescriptlang.org中没有错误
。但是仍然向我显示一个错误,本地计算机中的类型“String”上不存在属性“newMethod”

我不知道为什么

这是我的
tsconfig.json

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
     "outDir": "./lib",
     "rootDir": "./src",
  }
}
我安装`@类型/节点


我找到了一些例子

// 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() {}
仅添加了导入语句,出现错误。真奇怪。我不知道为什么?

这就是我为“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;
};

您在哪里定义打字?请提供一个我不确定是否可以在这里完成,但我有类似的问题“如何更改外部模块接口”:@DanielA.White我添加了示例,我还想知道示例2出现错误的原因?就因为你有进口声明?