Skip to content

Generic keyof deduction does not use Interface #39612

Description

@kwasimensah

TypeScript Version: 3.7.x-dev.201xxxxx

Search Terms:
generic deduction interface

Code

export type Param = number | string | boolean | Date | null;

export type ParamFields<T> = {
  [P in keyof Required<T>]: NonNullable<T[P]> extends Param ? P : never;
}[keyof T];

interface IHasId {
    id: number;
}

class HasId implements IHasId {
    id: number = 1;
}

function hasField<T>(x: T, field: ParamFields<T>) {
    return x[field];
}


hasField({ x: 5 }, "x");

function templateHasId<T extends IHasId > (x: T) {
    return hasField(x, "id"); // Doesn't realize id has to be a field of x.
}

Expected behavior:

hasId(x, "id"); compiles because it'd declared to have a field of x thats of type number.

Actual behavior:

Compains because it can't deduce "id" is a keyof T even though the interface says it is.

Playground Link:

https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=26&pc=1#code/KYDwDg9gTgLgBDAnmYcAKBDKGC2cC8cAdgK44BGwUcAPnAM4xQCWRA5rXORBADbAYinACIYYqOqV68A3ACg5oSLATJUmbDgBizYLwAm9ADwAVAHwE4Abzlw4AbTRxWcANbBEEAGZwASsABHEmYoYH1TMwBdAC44ADkIIjiSaQxyflNHSItQcSJDdCxcOAB+dDhYomAANyp5AF97d08fE0j5OVZxKC8MAGNUAEkACQx6Qf1rWztnfUqySigGhT7eMfo4UfHJ5hwwfhxgIhgNkbGJqZnZ+YoqSwBGZbkvEiI+mGZEuAALMZ09cLmAAUIFiJgANHAvLoDLENLh-gZjOYAJSXGahGAkKBCED2aEA9pyeoKOS-eiI-RAqxwUFwACscHqkIARCAWSiOi83h8vuI9mtxFsJqY4LkjgUzts4BYQWC0TYrpjsUJyZSQazmPoOTI4AB6PVwYQQYD0IgAcngoQwvGYAC9UFqfmMEBAuKgMFCYZNvLSAHTEhRAA

Related Issues:

#19211
#7294

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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