Microsoft/TypeScript

String.replace does not accept string | (string, ...any[]) => string replacer

开放

#22,378 创建于 2018年3月7日

 (9 条评论) (9 个反应) (0 位负责人)TypeScript (13,395 个派生)batch import
BugDomain: lib.d.tsHelp Wanted

仓库指标

星标
 (108,860 个星标)
PR 合并指标
 (PR 指标待抓取)

描述

TypeScript 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)

贡献者指南