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?
Record when declaring the reduce function:const metaObj = metaArr.reduce<Record<string, Meta>>((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
Meta interface for the initial object:const metaObj = metaArr.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {} as { [key: string]: Meta });
Record to cast the initial object:const metaObj = metaArr.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {} as Record<string, Meta>);
Thanks in advance.
Although this may be a trivial example there are some opinionated considerations to be discussed. Preferring one representation over the other is inherently subjective. Each solution functionally achieves the exact same result as any other, and the "testability" of each are also equivalent.
So based on your code, here are some things I may think about in order to help me with similar decisions:
reduce<Record<string, Meta>> is one of the first things you see when reading the code and without having scroll a potentially large reduce projection, it is clear the shape it will produce.{ [key: string]: Meta } is generally not as readable as the first point type declarations using Record<T, R> and there's more to write to achieve the same goal{} as Record<string, Meta>: using as "assertions" is by no means a code smell, but referring to the first point again, readers of your code will need to look for the resultant type of the reduce by going to the bottom of the function Usually when faced with these kinds of questions, all roads lead to the readability of your code. And while readability is also inherently a subjective pursuit, the more explicit and contained things are, generally, the easier it is to infer what a block of code is attempting to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With