Microsoft/TypeScript

Notes about `String.replace`

Open

#54,387 创建于 2023年5月25日

在 GitHub 查看
 (4 评论) (2 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: lib.d.tsHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

(Moved from rom https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1562)

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: https://github.com/microsoft/TypeScript/issues/54223

贡献者指南