Skip to content

Bug Report: TS creates contravariant intersection when K extending keyof T assigned new typeΒ #54547

Closed
@RoboZoom

Description

@RoboZoom

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions