How do you assert the type of a component as prop?

Viewed 69

I am trying to pass a component as prop.

The component:

export type ItemProps= {
  //...
};

export const Item = ({ /* ... */ }: ItemProps) => {
  return (
    //...
  );
};

Where I'm attempting to pass it:

type ParentProps= {
  //...
  item: ReactElement<ItemProps>;
};

export const Parent = ({ /* ... */, item }: ParentProps) => {
  return (
    <>
      {item}
    </>
  );
};

What I'm trying to achieve:

export const Main = () => {
  return (
    <Parent item={ <Item /> } />
  );
};

As you can see, I am trying to pass the Item component as a prop in the Parent component. As of now, this works, but it seems that using ReactElement loosens the type to ReactElement<ItemProps, string | JSXElementConstructor<any>>, or more generally:

ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>>.

The issue: if I were to replace with any other component, there wouldn't be any explicit warning or error about the component being different. I am trying to instead narrow it such that only the <Item /> component can be passed for the item={} prop of <Parent />.

In essence, what are some ways that can explicitly define a specific React component as a prop for a parent React component?

1 Answers

Because the Component returns JSX.Element, And the JSX.Element was extended from ReactElement.

interface Element extends React.ReactElement<any, any> { }

And I think if you want to assert the component that receives from the parent Component, you can receive the complete component like this

Related