TypeScript · Middle · Question 4 of 75

How do you type getProp(obj, key) so the result depends on the key?

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.

Further reading

Problem with a question

TypeScript · Middle · question 4

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz