[英]Why I cannot add a new method to String.prototype in typescript
I want to add a new method to String.prototype
. 我想向
String.prototype
添加一个新方法。 I tried this. 我试过了
interface String {
newMethod(): void
}
String.prototype.newMethod = function() {}
No errors in typescriptlang.org playground
. 在
typescriptlang.org playground
没有错误。 But still show me a error Property 'newMethod' does not exist on type 'String'
in my local computer. 但仍然显示错误我的本地计算机
Property 'newMethod' does not exist on type 'String'
。
I don't know why. 我不知道为什么
Here is my tsconfig.json
这是我的
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"outDir": "./lib",
"rootDir": "./src",
}
}
I install `@types/node 我安装`@ 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. 仅添加了import语句,发生错误。 So strange.
这么奇怪。 I don't know why?
不知道为什么
This is what I did for a "replaceAll" 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;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.