TypeScript · Senior · Question 69 of 75

How do you type a function that preserves the exact keys of an object passed to it while transforming values?

function mapValues<T extends object, R>(obj: T, fn: (v: T[keyof T]) => R): { [K in keyof T]: R } { /* ... */ }

Explanation

Callers keep autocompletion and typo checks on keys. Note Object.entries inside still loses key types and needs a cast.

Further reading

Problem with a question

TypeScript · Senior · question 69

Test yourself

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

Take this quiz