String.replace does not accept string | (string, ...any[]) => string replacer
See original GitHub issueTypeScript Version: 2.7.2
Search Terms: String.replace overload union parameter
Code
type ReplacerFn = () => string;
type Replacer = string | ReplacerFn;
function replaceFoo(str: string, replacer: Replacer) {
return str.replace(new RegExp("foo"), replacer);
}
Expected behavior: Compiles successfully.
Perhaps the change is as simple as combining the two overloads into a union, though the implications of that change are possibly unpleasant as far as tooling is concerned.
Actual behavior:
bad.ts(5,43): error TS2345: Argument of type 'Replacer' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'. Type 'string' is not assignable to type '(substring: string, ...args: any[]) => string'.
Playground Link: playground link
Related Issues: #20432 (Array.from) #20215 (new Date) #14107 (underlying issue)
Issue Analytics
- State:
- Created 6 years ago
- Reactions:5
- Comments:9 (2 by maintainers)
Top Results From Across the Web
String.prototype.replace() - JavaScript - MDN Web Docs
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement. The pattern can...
Read more >java - String replace method is not replacing characters
You aren't doing anything with the return value of replace . You'll need to assign the ...
Read more >String.Replace Method (System) - Microsoft Learn
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string, using...
Read more >Java String replace() method - javatpoint
The replace() method throws the NullPointerException when the replacement or target is null. The following example confirms the same. FileName: ReplaceExample4.
Read more >preg_replace - Manual - PHP
When using the deprecated e modifier, this function escapes some characters (namely ' , " , \ and NULL) in the strings that...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@jbccollins in our codebase we currently use something like this very ugly snippet:
Holy shit. I was really convinced it was valid and it seemed to work. 😒 (but it does not make sense) That’s why I’m moving to Typescript. Thank you very much @cpplearner.