Typescript: constrain argument of function to be a key of an object associated with a value of a particular type
问题 Is there a way to make the following type check? function getNumberFromObject<T>(obj: T, key: keyof T): number { return obj[key] // ERROR: obj[key] might not be a number } I want to specify that key should not only be a key of T , but a key with a number value. 回答1: The most straightforward way to do this so that both the callers and the implementation of getNumberFromObject<T> type check correctly is this: function getNumberFromObject<T extends Record<K, number>, K extends keyof any>( obj: T