I’m using the Array reduce function to create a keyed object representation of an array. I have a working solution already, but noticed there are multiple ways to ensure the output object is type-safe.
Given that I have the following interface and array:
interface Meta {
name: string;
value: string;
}
const metaArr: Meta[] = [
{ name: 'a', value: 'hello' },
{ name: 'b', value: 'hi' }
];
Out of the following three solutions, are any of them generally preferred, or is there a better way to do this?
- Use
Recordwhen declaring thereducefunction:
const metaObj = metaArr.reduce<Record<string, Meta>>((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
- Declare dynamic keys mapped to the
Metainterface for the initial object:
const metaObj = metaArr.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {} as { [key: string]: Meta });
- Use
Recordto cast the initial object:
const metaObj = metaArr.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {} as Record<string, Meta>);
Thanks in advance.