I'm trying to convert an array of classes to a object that has it's class name as the object key. So;
I have an array of classes:
const renderers = [
Battery,
Kind
]
And I want to convert to an object like:
{
Battery: Battery,
Kind: Kind
}
To get to that, I use reduce to get the Object:
const convertedObject = renderers.reduce((acc, renderer) => {
acc[renderer.name] = renderer;
return acc;
}, {});
So convertedObject now has a type of {}. I want this type to be { Battery: typeof Battery, Kind: typeof Kind} (so that I can use keyof typeof to create a type with the string values.)
I know how to get the type of the array by doing type RendererType = typeof renderers[0], which gets me typeof Battery | typeof Kind. Then in the reducer I can do this:
renderers.reduce<{[x: string]: RendererType }>((acc, renderer) => {
acc[renderer.name] = renderer;
return acc;
}, {});
So now, convertedObject has a type of { [x: string]: typeof Battery | typeof Kind }, which is ok. But I rather it be the object I described earlier.
I tried to do
renderers.reduce<{[K in keyof RendererType]: RendererType }>((acc, renderer) => {
acc[renderer.name] = renderer;
return acc;
}, {});
But then I just get { prototype: typeof Battery | typeof Kind }
Is there a way to get the type that I would need with Typescript somehow?