Skip to content

Prefer union type parameters instead of function overloads #46925

@rveerd

Description

@rveerd

lib Update Request

The type definitions for String.replace and String.replaceAll are written using overloads. Should they not be written with union type parameters?

Overloads give problems when creating wrapper functions for String.replace; see example below.

This has already been proposed in this comment in another issue but I cannot find a follow-up issue or discussion.

The documentation describes a similar problem and also advises to prefer union types, when possible.

Sample Code

export class Foo {
  constructor(
    private name: string
  ) { }

  replace(searchValue: RegExp | string, replaceValueOrReplacer: string | ((substring: string, ...args: any[]) => string)): string {
    return this.name.replace(searchValue, replaceValueOrReplacer);
  }
}
src/stream.ts:7:43 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type 'string | ((substring: string, ...args: any[]) => string)' is not assignable to parameter of type '(substring: string, ...args: any[]) => string'.
      Type 'string' is not assignable to type '(substring: string, ...args: any[]) => string'.

7     return this.name.replace(searchValue, replaceValueOrReplacer);
                                            ~~~~~~~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.es5.d.ts:454:5
    454     replace(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions