Skip to content

TypeScript fails to infer generic key K when constrained by T[K]'s type and T is inferred from thisΒ #61611

Closed
@wenerme

Description

@wenerme

πŸ”Ž Search Terms

  • unable to infer this in setter
  • ts2345

πŸ•— Version & Regression Information

seems all version behavied the same

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/C4TwDgpgBAogdsAlqKBeKBvKiAmAuKAZ2ACdE4BzKAXwG4Aoe0SKAJQHsAbCeJFdDPSjZ8RUuQoM6jAMacAhoUJQAqoQgleyEJiEiAhAWJlKDPSS4RDbS1tBnh64FAvcAkjgAUuI+MoBKXWFHCGA7EFYIADNPYAALREIAGigAIlcIVJTcfwZgqAB6AvyS0uEAPSgAQRIKAFcAWwgEKHYoqGZoAHJjCS7sZTh2Z0VCRAo4eQAjbg72KDB5Enkm4A1W9s6oLvjEgG0AawgQNo6EwgBdKAgADzW4HGVwqAB+KCOTzfOoAjgIADcNF0AHSeABMAGYACwAVn8ehCYQQ2kiMV2ykUqnUmmRoBS6UsWREuT01HoZPoUTqcBkSHYcCIoXCqIAPHoACrXO7NR6wXEgJJ6ADSXPuvME+T2AAVsAyPqd2RcCOzpVdbmKnvzXlAZb8ARo8jRDscFRd6AA+TzsADufxIypSHwIQpS9rEJgogQwZKAA

πŸ’» Code

type Entity = { id: string };

type RoleEntity = {
  id: string;
};

class UserEntity {
  id!: string;

  role!: RoleEntity;

  set roleId(id: string) {
    setEntityRef(this, "role", id);
    //                 ^ Argument of type 'string' is not assignable to parameter of type 'this[keyof this] extends Entity ? keyof this : never'.(2345)
    setEntityRef(this as UserEntity, "role", id);
  }
}

function setEntityRef<
  T extends Entity,
  K extends {
    [P in keyof T]: T[P] extends Entity ? P : never;
  }[keyof T]
>(owner: T, key: K, r: string) {}

πŸ™ Actual behavior

this type is this instead of current.

πŸ™‚ Expected behavior

works, can infer the fields

Additional information about the issue

No response

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