【发布时间】:2020-11-24 13:05:59
【问题描述】:
我需要为String.prototype.replace 保留一组输入。当尝试根据函数本身的类型定义一个接口以用作该数组的类型时,TypeScript 正在拒绝并出现 TS2769 错误。
代码:
interface Replacment {
searchValue: RegExp;
replacer: string | ((substring: string, ...args: any[]) => string);
}
const r1 = {searchValue: /bc/, replacer: 'de'};
const r2 = {searchValue: /bc/, replacer: () => 'de'};
const r3: Replacment = {searchValue: /bc/, replacer: 'de'};
const r4: Replacment = {searchValue: /bc/, replacer: () => 'de'}; // or (_substring: string, ..._args: any[]) => 'de'
'abc'.replace(/bc/, 'de');
'abc'.replace(/bc/, () => 'de');
'abc'.replace(r1.searchValue, r1.replacer);
'abc'.replace(r2.searchValue, r2.replacer);
'abc'.replace(r3.searchValue, r3.replacer); // <-- TS2769
'abc'.replace(r4.searchValue, r4.replacer); // <-- TS2769
错误:
(属性)Replacement.replacer:字符串 | ((子字符串:字符串,...args:任何[])=>字符串) 没有重载匹配此调用。 最后一个重载给出了以下错误。 'string | 类型的参数((substring: string, ...args: any[]) => string)' 不能分配给 '(substring: string, ...args: any[]) => string' 类型的参数。 类型 'string' 不可分配给类型 '(substring: string, ...args: any[]) => string'.(2769)有什么想法吗?
replace 定义为:
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;
【问题讨论】:
-
这是this github issue.的副本
标签: typescript