I want to convert an array of {key:'A',value:'B'} to an indexed object {A:{key:'A',value:'B'}}. How can I define the return type to reflect the result object ?
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
EDIT
Thanks to @Niilo Keinänen, the answer is very close, I changed to param to array, also works.
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;
}
toObject([{ key: 'first', value: 'second' }])= { first: { key: 'first', value: 'second' }}