microsoft / microsoft/TypeScript

Type inference for `Function.call` return type on generic functions

Open
#54,319 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

type infer function call generic

⏯ Playground Link

Playground link with relevant code

💻 Code
function numberEcho(x: number): number {
    return x;
}

function genericEcho<T>(x: T): T {
    return x;
}

// This works
const resultNumber: number = numberEcho.call(this, 1);

// Type Error: Type 'unknown' is not assignable to type 'string'.(2322)
const resultString: string = genericEcho.call(this, 'hello');
🙁 Actual behavior

Type inference of genericEcho.call return type failed even when all the argument types are known at call site.

Of course explicitly hinting the return type would work but it's not good:

const resultString: string = genericEcho.call<typeof this, [string], string>(this, 'hello');
🙂 Expected behavior

I would expect type inference of generic function return type to work if all arguments types are known.

I think #40179 is related but the example I provided here is much more common since it exists in standard library.

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 with the linked TypeScript Playground and compare the inferred return types for the direct and generic Function.call examples. Done means the generic call infers the argument type and accepts the result as a string, with the existing behavior still covered by an appropriate regression check.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.