2

Based on this answer, I have some example code as follows. It works fine with no generic as in the cited answer, but fails as soon as I try to make the type a generic instead of Thing:

declare function takesNumber(arg0: number): boolean;
interface Thing {
    id: string;
    price: number;
    other: { stuff: boolean };
}
type KeysMatching<T, V> = {[K in keyof T]-?: T[K] extends V ? K : never}[keyof T];
const noGeneric = function(
    vector: Thing,
    selectedAttributeName: KeysMatching<Thing, number>,
) {
    takesNumber(vector[selectedAttributeName]);
}
const withGeneric = function<T>(
    vector: T,
    selectedAttributeName: KeysMatching<T, number>,
) { //sometimes we need T as a generic to constrain other parameters, return type, etc.
    //Error: Argument of type 'T[KeysMatching<T, number>]' 
    //is not assignable to parameter of type 'number'.
    takesNumber(vector[selectedAttributeName]);
}

WBT
  • 2,249
  • 3
  • 28
  • 40
  • You've run into [ms/TS#30728](https://github.com/microsoft/TypeScript/issues/30728); the easiest fix is to reverse your generics like [this](https://tsplay.dev/mbKqoW). See the answer to the linked duplicate question for more details – jcalz Jan 27 '23 at 17:41

0 Answers0