How to pass prop to a component using React and typescript?

Viewed 36

Hi there is a component FormField and that accepts either of one icon create or edit. Now I use this FormField within another component SelectWithFormField

Like so:

const FormField = ({create, edit}: FormFieldProps) => {
    const iconTooltip = create ? {create}: edit ? {edit} : undefined;
    return (
        <Label {...iconTooltip} />
    );
}

const SelectWithFormField = <T1, T2>) =>  (
    <FormField //error here
        create={create}
        edit={edit}
    />
);

This SelectWithFormField will be called by other components where one will be called with edit and other with Create. I want to do so such that I can use SelectWithFormField with edit icon in some pages and with create icon in other pages.

const Main1 = () => {
    <SelectWithFormField edit={edit} />
}

const Main2 = () => {
    <SelectWithFormField create={create} />
}

But since FormField accepts either of create or edit props I am not able to pass 2 props together in SelectFormField component. How can I fix this. could someone help me with this. thanks.

EDIT:

type FormFieldProps = {
    fieldId: string;
} & IconTooltipProps;

type IconTooltipProps = EditTooltipProps | CreateTooltipProps;

type EditTooltipProps = {
    create?: never;
    edit?: string;
}

type CreateTooltipProps = {
    create?: string;
    edit?: never;
}
1 Answers

What about something like this?

interface CreateTooltipProps {
    create: string;
    edit?: string;
}

interface EditTooltipProps {
    edit: string;
}

type IconTooltipProps = CreateTooltipProps | EditTooltipProps;

If you pass create as a prop, edit is optional. If create is not passed, edit is required.

Related