microsoft / microsoft/TypeScript

Infering type of optional parameter of lambda function is broken when passed to generic function.

Open
#33,852 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

TypeScript Version: 3.7.0-beta, nightly and older ones

Search Terms:
optional parameter infer lambda generic
Code

declare function noop<T>(val: T): T;

const f = (a: string, b = 23) => b;

// reports "Parameter 'b' implicitly has an 'any' type."
// broken since v3.5.1, older versions work well
const foo = noop((a: string, b = 23) => b);  

// (a: string, b?: number) => number
const bar = noop(f);
 
declare function noop2<T extends (...params: any[]) => any>(val: T): T;

// (a: string, b?: any) => any (BUG)
const foo2 = noop2((a = 23) => a);  // broken on all versions

// (a: string, b?: number) => number
const bar2 = noop2(f);

Expected behavior:

foo* and bar* should all have the same type.

Actual behavior:

In the first case, the compiler complains that it can't infer the type of optional argument of lambda forwarded to noop, and in the second case it silently assigns any type to b instead of number

Playground Link:

https://www.typescriptlang.org/play/?ts=Nightly&ssl=11&ssc=23&pln=1&pc=1#code/CYUwxgNghgTiAEAzArgOzAFwJYHtX1RxwAcAeAFQD4AKANyggC55yBKZ8gbgFgAoPlOmx4k1KMwDOGGFlQBzADTwARvAC88AEwBmVvADe8OBmQx8UTvAC+fPmDxSkRdQSLFqYydNmKVLnXpqlPBQrJZ2DhgqsC6EJNSIYXzwfKCQsAiCmLj4ccSaFPAgAB4YIKjAEvDUAHR1xLBQALYSzFCoAJ4A2gC6gcHtHTT0TCzsLDz8vPaojohEmrFumh7i8FIy8kqqGgHqA2Ep05HRMIsaeSuJnEA

Notes
The mentioned versions of typescript are not exact, I just used TypeScript playground and the set of available versions there.

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 reproducing the examples in the linked TypeScript Playground, especially the calls to noop and noop2 with optional lambda parameters. Trace the compiler's generic inference and contextual typing for those expressions. Done means foo, bar, foo2, and bar2 infer equivalent parameter and return types without an implicit any error.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.