打字稿-版本:1.6打字稿上基本字符串类型重载方法
我想添加另一个重载函数为String
小号replace
- 函数应该具有以下特征:
replace(searchValue: string, replaceValue: any): string;
因此,它可以用于像
"someString".replace("replaceMe", $(evt.target).data("row-id"))
我需要any
为.data
定义为:
data(key: string): any;
我String.d.ts
(声明)
interface String {
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A string that represents the regular expression.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: string, replaceValue: any): string;
}
我String.ts
(实现)
String.prototype.replace = (searchValue: string, replaceValue: any):string =>
{
if (replaceValue instanceof String) {
var stringReplacement = replaceValue.toString();
return String.prototype.replace(stringReplacement, replaceValue);
} else {
return replaceValue;
}
}
下引发错误,我不知道为什么,以及如何修复:
错误TS2322 Type'(searchV alue:string,replaceValue:any)=> string'不可分配给类型'{(searchValue:string,replaceValue:string):string; (searchValue:string,replacer:(substring ...') 参数'searchValue'和'searchValue'的类型不兼容 类型'string'不能分配给'RegExp'类型 'exec'缺少键入 '字符串'
编辑#1
我结束了刚刚声明replace
(和实施的消除方法),以满足编译器:
interface String {
/**
* Replaces text in a string, using a regular expression or search string.
* @param searchValue A string that represents the regular expression.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: string, replaceValue: any): string;
}
这仍然是错误的,因为它仍然称为图书馆的replace
功能?
编辑#2
如果使用没有自己的Visual Studio大喊大叫
随着投它显示(ReSharper的)与实例4.1(
MartyIX)
所以,我不知道打字稿什么,但我看不出有什么这个方法做,你已经不能用'String.prototype.replace'做什么? – Mathletics
似乎TS函数对参数类型不变,而'f(string,any)'不能保存为'f(string,string)'类型的值。 –
@Mathletics它在编译时得到了一个错误,因为在typescript中没有'replace(string,any)的定义' – KingKerosin