对于以下类似的函数[].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: "[email protected] /cdn-cgi/l/email-protection",
}
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 2.1 发行说明 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html#partial-readonly-record-and-pick.
结合你的代码我最终得到:
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U> {
return Object.keys(obj).reduce((ret, key) => {
const k = key as K;
ret[k] = f(obj[k]);
return ret
}, {} as Record<K, U>)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)