Microsoft/TypeScript

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

Open

#22 378 ouverte le 7 mars 2018

Voir sur GitHub
 (9 commentaires) (9 réactions) (0 assignés)TypeScript (6 726 forks)batch import
BugDomain: lib.d.tsHelp Wanted

Métriques du dépôt

Stars
 (48 455 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (9 PRs mergées en 30 j)

Description

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)

Guide contributeur