Description
Bug Report
π Search Terms
T[K] assignment does not transform type of T
π Version & Regression Information
Version: 4.8.4 to Present
This is bug became relevant when 4.8.4 released.
β― Playground Link
Playground link with relevant code
π» Code
const joinSample = <T, K extends keyof T, U extends HasID>(
parent: T,
parentKey: K,
children: U[],
) => {
const keyArray = parent[parentKey] as string[];
return {
...parent,
[parentKey]: keyArray.map((k) => findOneById(children, k)) // Returns type U | undefined
};
}
π Actual behavior
The above code infers the output to joinSample
as T & [x: string] : (U | undefined)[]
which indicates that the T has the same key twice, with different types.
This is demonstrated in the playground when joined
is typed to FullFoo
. Untyped, when run, it produces an object that meets the criteria for FullFoo
. When declared with type FullFoo
, it raises an error.
π Expected behavior
I would expect Typescript to substitute the type of parentKey from its previous value (in this case, always string[]
) to (U | undefined)[]
. The compiler knows that K is a keyof T - instead of creating a never
condition, it should replace the type of T[K] to U.