microsoft / microsoft/TypeScript

Wrong overload selected on function when passed a callback annotated with a type with multiple optional properties

Open
#20,305 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: 2.7.0-dev.20171128

Code

This issue was first noticed in code that uses LoDash with the typings from DefinitelyTyped. It seems to manifest only in a very specific set of circumstances. The following code sample is as minimal a reproduction as I could find.

let _: LoDashStatic;

interface LoDashStatic {
  mapValues<T extends object, TResult>(
    obj: T,
    callback: (value: T[keyof T]) => TResult
  ): { [P in keyof T]: TResult };

  mapValues<T extends object>(obj: T, iteratee: object): { [P in keyof T]: boolean };
}

interface Item {
  key?: string;
  bar?: number;
}

interface Collection {
  [key: string]: Item;
}

const source = { foo: { bar: 42 } };
let items: Collection = _.mapValues(
  source,
  (v: Item) => v
);

Note that the correct overload is selected when any of the following changes are made to the above code:

  • Remove the type annotation on the callback: (v) => v instead of (v: Item) => v
  • Remove the nested optional property: { foo: {} } instead of { foo: { bar: 42 } }
  • Remove the unused optional property: interface Item { bar?: number; } instead of interface Item { key?: string; bar?: number; }
  • Annotate the source collection: const source: Collection = { foo: { bar: 42 } }; instead of const source = { foo: { bar: 42 } };

Expected behavior:

Compiles without issue.

Actual behavior:

error TS2322: Type '{ foo: boolean; }' is not assignable to type 'Collection'.
  Property 'foo' is incompatible with index signature.
    Type 'boolean' is not assignable to type 'Item'.

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 minimal TypeScript reproduction in the issue and investigate overload resolution for the annotated callback, optional properties, and inferred source type. Done means the sample compiles without the TS2322 error and selects the callback overload rather than the object-iteratee overload.

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
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.