【发布时间】:2020-06-09 23:36:49
【问题描述】:
对于以下类似于[].map但针对对象的函数
function mapObject(f, obj) {
return Object.keys(obj).reduce((ret, key) => {
ret[key] = f(obj[key])
return ret
}, {})
}
有没有办法输入它以便以下工作?
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'
这可行,但非常特定于 applyChanges 函数
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>
有没有更通用的解决方案?
【问题讨论】:
标签: typescript