Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Notes about String.replace #1562

Closed
m-gallesio opened this issue May 12, 2023 · 2 comments
Closed

Notes about String.replace #1562

m-gallesio opened this issue May 12, 2023 · 2 comments

Comments

@m-gallesio
Copy link

m-gallesio commented May 12, 2023

I am using TypeScript 5.0.4.
I have noticed the typing of String.replace seem oddly convoluted.

From lib.es5.d.ts:

interface String {
    replace(searchValue: string | RegExp, replaceValue: string): string;
    replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
}

From lib.es2015.symbol.wellknown.d.ts:

interface String {
    replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
    replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
}

Like the first parameter is declared as an union, I would expect the second to be the same, at least in the lib.es5 version.

Notably, this makes the following code not compile:

// The second argument is an union of replaceValue and replacer from lib.es5
const replacementSteps: ([RegExp, string | ((substring: string, ...args: any[]) => string)])[] = [
    [/(a|b)/gi, "a"],
    [/(c|d)/gi, match => match.toUpperCase()],
];

let myString = "abcdef";

for (const [searchValue, replacement] of replacementSteps)
    myString = myString.replace(searchValue, replacement); // TS2345 - the second parameter is considered invalid

By adding this into my declaration, the code works:

declare interface String {
    replace(searchValue: string | RegExp, replaceValue: string | ((substring: string, ...args: any[]) => string)): string;
}

I cannot propose a solution other than my last hack, and of course the variants with Symbol would have to be taken into account. Please consider this just a note.

See also this: microsoft/TypeScript#54223

@saschanaz
Copy link
Contributor

Hi, this repository only covers non-JavaScript APIs, and issues about JavaScript ones should go microsoft/TypeScript repo.

@m-gallesio
Copy link
Author

Understood; moving it there.

@m-gallesio m-gallesio closed this as not planned Won't fix, can't repro, duplicate, stale May 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants