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;
}
Did I understand correctly:
toObject({ key: 'first', value: 'second' })
= { first: 'second' } ?
This would seem to work:
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
}
Maybe you could also avoid the dirty any type somehow, not sure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.