More specific than ReactNode?

Viewed 313

I defined props for a component:

interface HeaderProps{
  title: string;
  image: string;
  link: ReactNode;
}

'link' refers to another component, <Link />

So I define it as a ReactNode.

Is there anything more specific I can use instead of ReactNode? Like typeof Link or just Link?

1 Answers

Typing to Allow Only Specific Component

Since React.ReactElement<> accepts any type of element, you can also make it strictly to accepts some specific component type. Let’s say you have a Header component that should only works if it receives a Link component. You can type it as the following

//link interface

interface Link {
  link: string
}

const Link = ({ children }: Link) => <span>{children}</span>


Then in your interface HeaderProps

interface HeaderProps{
  title: string;
  image: string;
  link: ReactElement<Link>;
}

// Correct usage
<Header>
....
<Link>Some content</Link>

</Header>

// Wrong usage
<Header>
...
<Link>{true}</Link>

</Header>

Related