TypeScript-Version: 1.6
I'm trying to add another overload-function for String
s replace
-function which should have the following signature:
replace(searchValue: string, replaceValue: any): string;
So it can be used like
"someString".replace("replaceMe", $(evt.target).data("row-id"))
I need any
as of .data
is defined as:
data(key: string): any;
My String.d.ts
(declaration)
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;
}
My String.ts
(implementation)
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;
}
}
The following error is thrown and I'm not sure why and how it can be fixed:
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'.
Edit #1
I ended up with just the declaration for replace
(and removement of the implementation) to satisfy the compiler:
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;
}
Is this still wrong as of internally it still calls the replace
-function of the library?
Edit #2
If using nothing own Visual Studio is yelling
With cast it shows (ReSharper)
With example 4.1 (MartyIX)
String.prototype.replace
? – Mathleticsf(string, any)
can't be saved into a value of typef(string, string)
. – Bartek Banachewiczreplace(string, any)
– KingKerosinany
<->string
can't be distinguished? – KingKerosin