TypeScript · Middle · Question 4 of 75
How do you type getProp(obj, key) so the result depends on the key?
- ✓Correct answer:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] - 2
function getProp(obj: object, key: string): unknown - 3
function getProp<T>(obj: T, key: keyof any): T
Explanation
K extends keyof T allows only existing keys, and the indexed access T[K] gives the exact value type: getProp(user, 'age') → number. The any version loses typing, and string lets typos through.