Home > Mobile >  Dynamically Set Type of Prop Based on Another Prop
Dynamically Set Type of Prop Based on Another Prop

Time:01-22

If I have an interface like the following:

interface Example {
    Component: React.ReactElement;
    componentProperties: typeof Example.Component;
}

Is there a way to get the type of the properties that that component passed in expects. So say I pass in a custom component like the following:

const Text = ({ value: string }) => <p>{value}</p>;

The type of componentProperties I would like to equal { value: string }


I think I am looking something closer to this where the typeof the Component is what determines the type for componentProperties:

interface Example<T> {
    Component: () => React.ReactElement;
    componentProperties: T;
}

const Comp = ({ value }: { value: string}) => <p>{value}</p>;

const blah = ({ Component, componentProperties }: Example<typeof Component>) => {
    return <Component {...componentProperties} />;
};

blah({
    Component: Comp,
    componentProperties: { value: 'test' }
});

This example is riddled with errors which is why I am having trouble.

CodePudding user response:

interface Example<T> {
    Component: React.ReactElement;
    componentProperties: T;
}

CodePudding user response:

Everything looks good except the blah, I would guess

there you get the errors.

This is how I solved this on my project.

const blah = ({ Component, componentProperties }: Example<typeof Component>) => {
    var Cm = Component as any;
    return <Cm {...componentProperties} />;
};
  •  Tags:  
  • Related