For the following function which is similar to [].map
but for objects
function mapObject(f, obj) {
return Object.keys(obj).reduce((ret, key) => {
ret[key] = f(obj[key])
return ret
}, {})
}
is there a way to type it so that the following works?
interface InputType {
numberValue: number
stringValue: string
}
interface OutputType {
numberValue: string
stringValue: number
}
const input: InputType = {
numberValue: 5,
stringValue: "bob@gmail.com",
}
function applyChanges(input: number): string
function applyChanges(input: string): number
function applyChanges(input: number | string): number | string {
return typeof input === "number" ? input.toString() : input.length
}
const output: OutputType = mapObject(applyChanges, input) // <-- How to get the correct 'OutputType'
This works, but is very specific to the applyChanges
function
type MapObject<T> = {
[K in keyof T]: T[K] extends number
? string
: T[K] extends string ? number : never
}
function mapObject<F extends FunctionType, T>(f: F, obj: T): MapObject<T>
Is there a more general solution?