Rename keys of an object/interface typesafe
问题 I want to dynamically rename keys with a mapping function. For this, I've made this: interface DateRange { startDate: string; endDate: string; } function format<K extends string>(range: DateRange, mapping: {[X in keyof DateRange]: K}): {[P in K]: string} { return { [mapping.startDate]: range.startDate, [mapping.endDate]: range.endDate, }; } When I cast the return value of this function with as {[P in K]: string} it all works fine, but without the cast it doesn't compile. Error Message: TS2322