microsoft / microsoft/TypeScript

Cannot infer generic argument type from passed callback

Open
#31,146 15 comments 8 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Cursed? Domain: check: Type Inference
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:

infer, parameter, argument, callback, function

Code

function inferArguments<T>(callback: ((t: T) => void)) {
  return callback;
}

function noop(){}

const explicit = inferArguments(({a = noop}: {a: Function}) => {});
explicit({a: noop}); // OK!
explicit({a: false}); // Expected error - Got one!

const implicit = inferArguments(({a = noop}) => {});
implicit({a: noop}); // OK!
implicit({a: false}); // Expected error - No Error!

Expected behavior:
Both function calls with ({a: false}) should cause a type error

Actual behavior:
Only the function call with the explicit typing causes a type error

Playground Link

Related Issues: #30975 Looks similar but seems different since there should be a clear way for inference to work in this case

Note that Parameters is correctly able to extract the correct types for such a construct as seen in this bit of code:

function noop() { }
function callback({ a = noop }) { }
let args: Parameters<typeof callback>;
args[0].a as Function

This appears to be an error with inline callback functions used in this fashion

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

Reproduce the explicit and implicit cases in the linked TypeScript Playground, then compare their inferred callback parameter types and the behavior of Parameters. The issue names no repository file or test; done means both calls using {a: false} produce type errors while the valid noop cases remain accepted.

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
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.