Skip to content

Generic properties are not correctly inferredΒ #57318

Closed as not planned
Closed as not planned
@markostanimirovic

Description

@markostanimirovic

πŸ”Ž Search Terms

"generic type inference"

πŸ•— Version & Regression Information

TS v5.3.3

It's not a regression.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/C4TwDgpgBAysBOBLAdgcwArwPZgM4B4BRZYRUAPigF4oBvAKCigG0BpKFKAawhCwDMoxUqCgBDXEJJkQbALpQIAD2ARkAE0m4EKVFAD8UdgC4oyCADcI8OaeEz5AbnoBfZ-VCRYOtJhyteImkKam5eAW8kX2w8IJEQcnd+AFdkAGNSLGQoABssVACQInIACh4QUzgojBjC4oBKOkYoNKzcLByIADo81DLeeucXenoU9Mzs62x4IkUVNU06KGTkxHVTbWqoF1LGhiZeusJSgHIVtZPB13ogA

πŸ’» Code

type StringProps<Entity> = {
  [K in keyof Entity as Entity[K] extends string ? K : never]: Entity[K];
};

type StringPropKey<Entity> = keyof StringProps<Entity>;

function logKey<E>(key: StringPropKey<E>) {
  console.log(key);
}

function error<E extends { uuid: string }>() {
  logKey<E>('uuid');
}

πŸ™ Actual behavior

Compilation error: Argument of type 'string' is not assignable to parameter of type 'keyof StringProps<E>'. Type '"uuid"' is not assignable to type '(E[K] extends string ? K : never) | (E["uuid"] extends string ? "uuid" : never)'

πŸ™‚ Expected behavior

There should not be a compilation error. As a workaround, we can explicitly check if E extends { uuid: string }:

function error<E extends { uuid: string }>() {
  // this
  logKey<E extends { uuid: string } ? E : never>('uuid');
}

but this should not be required because E already extends { uuid: string }.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions