Trying to create a dynamic React component. What is the proper way to conditionally pass the correct propType based on the selected component. Here's what I have so far I'm getting an error on this line <SelectComponent {...props.props} /> because the props don't match the components:
export interface SidebarProps {
type: keyof typeof components,
props: AddEditJobsProps | AddEditCustomersProps
}
const components = {
job: AddEditJobs,
customer: AddEditCustomers
};
export default function Sidebar(props: SidebarProps) {
const { open, toggle } = useToggle();
const SelectComponent = components[props.type];
return (
<RightSidebar open={open} toggleDrawer={toggle}>
<SelectComponent {...props.props} />
</RightSidebar>
);
}
Edit: adding any to the props fixes the error however Typescript won't be able to match the selected type with the corresponding props during type checking which is what I'm hoping to accomplish here.
export interface SidebarProps {
type: keyof typeof components,
props: AddEditJobsProps | AddEditCustomersProps | any
}
SelectComponentcould be eitherAddEditJobsorAddEditCustomersdepending on the value ofprops.type?props.props? The former might be possible, but the latter is impossible because the actual type ofSelectComponentwill be unknown until runtime and can not be inferred by Typescript.