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]);
}