TypeScript 版本: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;
}
}
抛出以下错误,我不知道为什么以及如何修复它:
Error TS2322 Type '(searchValue: string, replaceValue: any) => string' is not assignable to type '{ (searchValue: string, replaceValue: string): string; (searchValue: string, replacer: (substring...'. Types of parameters 'searchValue' and 'searchValue' are incompatible. Type 'string' is not assignable to type 'RegExp'. Property 'exec' is missing in type 'String'.
编辑#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)
最佳答案
执行 "someString".replace("replaceMe", $(evt.target).data("row-id"));
应该有效,因为 any
可以被分配给字符串
。我不确定您为什么会收到错误,但我建议确保以 string
作为 replace
的第一个参数的函数签名尚未从lib.d.ts
。您可以通过转到替换的定义(将光标放在替换上并按 F12)并确保它具有下面显示的所有函数签名来仔细检查。您还可以尝试暂时禁用 resharper,看看是否会使错误消失。
顺便说一下,要通过重写 String.prototype.replace 来修复错误,它已经具有这些可能的函数签名:
replace(searchValue: string, replaceValue: string): string;
replace(searchValue: string, replacer: (substring: string, ...args: any[]) => string): string;
replace(searchValue: RegExp, replaceValue: string): string;
replace(searchValue: RegExp, replacer: (substring: string, ...args: any[]) => string): string;
当 searchValue
是 RegExp
时,编写的内容不兼容,因此您需要更改函数签名以允许 string
和 RegExp
通过使用联合类型:
String.prototype.replace = function(searchValue: string | RegExp, replaceValue: any) {
// omitted
}
我不确定你想做什么,因为该函数将执行无限循环。也许您打算保留对原始 String.prototype.replace 的引用并调用它?请记住,当您分配给 String.prototype.replace
时,您会覆盖原始函数。
总的来说,不要做这里正在做的事情。请查阅“不要修改不属于您的对象”以了解我的意思。如果您创建自己的单独函数来执行此操作会更好,因为现在此替换函数会破坏任何使用它的代码。如果您使用的任何库使用 replace
方法,您会得到非常奇怪的行为,并且很难追踪问题。
关于javascript - 基本类型字符串的 TypeScript 重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152181/