I have an array of elements, each with a unique category
string property. I aim to transform this into a structure where the category serves as the key and the original element is the value.
To tackle this, I first verify that I possess a correctly typed tuple
type ElementType = { category: string; [key: string]: any }
const createList = <T extends ReadonlyArray<ElementType>>(items: T) => items;
const elementList = createList([
{ category: 'x', data: 'example' },
{ category: 'y', data: 20 },
] as const)
// elementList[0].data is accurately inferred as 'example'
// elementList[1].data is accurately inferred as 20
Next, I endeavor to convert it into an object type.
type ElementDictionary = {
[index in typeof elementList[number]['category']]: typeof elementList[number];
}
const categorized: ElementDictionary = undefined as any;
The dilemma here is that the value ends up becoming a union type of all possible values instead of being specific to that particular key, resulting in
type ElementDictionary = {
x: { data: string | number };
y: { data: string | number };
}
instead of
type ElementDictionary = {
x: { data: string };
y: { data: number };
}
Any insights on how to achieve individual item types in ElementDictionary
?
Note: this code snippet is not from my current project; I have simplified the main issue for clarity