Closed
Description
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:
Related Issues: