microsoft / microsoft/TypeScript

Generic inference of Overloaded methods only working with the last defined method

Open
#43,187 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Docs
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Bug Report

🔎 Search Terms
  • Generics
  • Overload
  • Type inference
🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about overloading
⏯ Playground Link

Playground link with relevant code

💻 Code
class SomeClazz {
    public overload(param: 'PARAM1'): number;
    public overload(param: 'PARAM2'): string;

    public overload(param: 'PARAM1' | 'PARAM2'): number | string {
        switch (param) {
            case 'PARAM1':
                return 1337;
            case 'PARAM2':
                return 'Hi';
        }
    }
}

function call<Ctx extends { [F in Name]: (this: Context, ...args: any[]) => any }, Name extends string>(
    ctx: Ctx,
    method: Name,
    ...args: Parameters<Ctx[Name]>
): void {
    ctx[method](...args);
}

const clazz = new SomeClazz();
clazz.overload('PARAM1'); // Works ok
clazz.overload('PARAM2'); // works ok
call(clazz, 'overload', 'PARAM1'); // ERROR: Argument of type '"PARAM1"' is not assignable to parameter of type '"PARAM2"'
call(clazz, 'overload', 'PARAM2'); // Works ok

Workbench Repro

🙁 Actual behavior
  • Only one function overload is taken into account when inferring function parameter types
🙂 Expected behavior
  • All function overloads should be taken into account when inferring function parameter types

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the linked Playground or Workbench repro and compare the two generic call sites with the direct overload calls. Trace how Parameters<Ctx[Name]> is inferred for the overloaded method; done means both call(clazz, 'overload', 'PARAM1') and call(clazz, 'overload', 'PARAM2') are accepted while preserving the reported overload behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.