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 } { /* ... */ }- ✓Correct answer: Use a mapped type over
keyof Tin the return type - 2Return
Record<string, R> - 3Return
object
Explanation
Callers keep autocompletion and typo checks on keys. Note Object.entries inside still loses key types and needs a cast.