Incorrect inference/autocompletion on generic arrays, when values can be inferred from a defined object.
#41.645 aberto em 23 de nov. de 2020
Métricas do repositório
- Stars
- (48.455 stars)
- Métricas de merge de PR
- (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)
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.

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:
allergensis optionnal- We switch from an interface to a type
- We use
keyof this['quantities']instead ofINGREDIENTS[]