microsoft / microsoft/TypeScript

Empty rest parameter type inferred from candidate function with no rest parameters when "best match" contains a contextually typed argument

Open
#52,227 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Help Wanted Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

Rest parameter inference contextual

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type inference
⏯ Playground Link

Playground link with relevant code

💻 Code
const doSomething = <Args extends unknown[]>(
    fn1: (aNumber: number, ...rest: Args) => void,
    fn2: (aNumber: number, ...rest: Args) => void,
) => {}

// OK, no contextual types
doSomething(
    (explicit: number, rest: string) => {}, // Args = [string]
    () => {},
)

// OK (both contain contextually typed arg)
doSomething(
    (contextual, rest: string) => {}, // Args = [string]
    (contextual) => {},
)

// Contextually type only fn1 - Not ok
doSomething(
    (contextual, rest: string) => {}, // ERROR
    () => {}, // Args = []
)
doSomething(
    (contextual, rest: string) => {}, // ERROR
    (explicit: number) => {}, // Args = []
)
🙁 Actual behavior

When fn1 (and only fn1) contains a contextually typed argument, it is ignored in favour of fn2

🙂 Expected behavior

In all of the examples, fn2 specifies no rest parameters at all.

I would expect functions that do not specify any rest parameters to always be the least preferable candidate (lowest weight?) for rest parameter inference, since "no rest parameters" can always be assigned to any rest parameter type.

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 reproduction and reduce the three doSomething calls to isolate how contextual typing affects rest-parameter inference. Trace the type-checking path that chooses inference candidates, then add a regression test for the shown cases; done when fn1's [string] rest type is not replaced by [] from fn2.

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.