[英]TypeScript: Infer specific types of arguments and return values of functions in a mapped object
[英]How to infer types of the transformed values of an object
我正在努力输入一个 function,它通过迭代 object 的每个属性并单独转换这些属性来转换 object。
const x = {a: 1, b: 'hello'};
const y = {c: 1, d: true};
function transform<T extends Object>(src:T): {[k in keyof T]: any[]} {
return Object.keys(src).reduce((acc, key) => ({...acc, [key]: [src]}), {}) as any;
}
// ideally typed {a: number[], b: string[]}
// actually typed {a: any[], b: any[]}
const xPrime = transform(x);
// ideally typed {c: number[], d: boolean[]}
// actually typed {c: any[], d: any[]}
const yPrime = transform(y);
在这种情况下,我将它们包装在 Arrays 中 - 但我希望该解决方案将帮助我解决其他容器类型的更复杂的问题。
谢谢!
只需将any[]
替换为T[k][]
:
function transform<T extends Object>(src:T): {[k in keyof T]: T[k][]} {
throw Error('unimplemented'); // Your implementation is weird
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.