我想将{key:'A',value:'B'}
的数组转换为索引对象{A:{key:'A',value:'B'}}
。如何定义返回类型以反映结果对象?
function toObject<T = any>(a: Iterable<T & { key }>): { [k in /* !!not like this!! */ keyof T]: T } {
return [...a].reduce((a, v) => (a[v.key] = v, a), {}) as any;
}
// Hope there is a hint for A and B
toObject([{key:'A',value:'B'},{key:'B'}]).A
编辑
感谢@NiiloKeinänen,答案非常接近,我将参数改为数组,也可以使用。
const toObject = <K extends string, T = any>(arr: Array<T & { value: K }>): { [k in K]: T } {
const obj: any = { };
arr.forEach(v => obj[v.value] = v);
return obj;
}
答案 0 :(得分:1)
我理解正确吗?
toObject({ key: 'first', value: 'second' })
= { first: 'second' } ?
这似乎可行:
const toObject = <K extends string, V, T extends { [P in K]: V }>(keyValuePair: { key: K, value: V }): T => {
const obj: any = {}
obj[keyValuePair.key] = keyValuePair.value
return obj as T
}
也许您还可以以某种方式避免不确定的 any 类型。