How do I map correct component props types in function return type based on function parameter (config)?

Viewed 19

I have a function, that accepts certain object (it's constant)

const config = {
  foo: {
    component: MyComponent1,
  },
  bar: {
    component: MyComponent2,
  },
};

I want function to return an object like this

const returned = {
  foo: WrappedMyComponent1,
  bat: WrappedMyComponent2,
};

Where ComponentN and WrappedComponentN has same props (almost same component type)

Here is my attempt

import { Box, TextField } from '@mui/material';

const remapComponents = <P, C extends Record<string, { component: ComponentType<P> }>, R extends Record<keyof C, ComponentType<P>>>(config: C): R =>
  Object.entries(config).reduce((prevValue, [key, conf]) => ({
    ...prevValue,
    [key]: (conf as { component: ComponentType<P> }).component,
  }), EMPTY_DATA_OBJ as R);

const result = remapComponents({ foo: { component: TextField }, bar: { component: Box } });

I managed to get correct keys in result - result.foo and result.bar, but the all get type of ComponentType<unknown>

How do I make resulting components to have correct props types?

0 Answers
Related