microsoft / microsoft/TypeScript

Incorrect inference/autocompletion on generic arrays, when values can be inferred from a defined object.

Open
#41,645 6 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: LS: Completion Lists Effort: Moderate Experience Enhancement Experimentation Needed Help Wanted Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 4.1.2

Search Terms:
Autocompletion, incorrect, values, inference, generic, array, object, keys

Summary:
When an interface/a type has an object with generic keys, and an array of those keys, the array values cannot be infered from the object keys.

Code

interface Recipe<INGREDIENTS extends string> {
  quantities: Record<INGREDIENTS, number>
  allergens?: INGREDIENTS[]
}

function createRecipe<INGREDIENTS extends string>(recipe: Recipe<INGREDIENTS>) {}

createRecipe({
  quantities: {
    eggs: 1,
    flour: 2,
  },
  allergens: ['']
})

Expected behavior:
Here, when trying to give a value to allergens, the autocompletion should show "eggs" | "flour".

Actual behavior:
The autocompletion doesn't find anything.
image

Notes:
The other way is working: you can fill the array first, then the object keys will autocomplete - but this rarely make sense to write things that way.

Failed workarounds:
This bug is still present, even when:

  • allergens is optionnal
  • We switch from an interface to a type
  • We use keyof this['quantities'] instead of INGREDIENTS[]

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 TypeScript 4.1.2 example from the issue, focusing on inference from the quantities object into the allergens array and its autocomplete results. Compare the reported behavior with the reverse ordering, and consider the issue done when "eggs" and "flour" are offered as completions for allergens without changing the example's generic types.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.