Is it possible to type check a components children with TypeScript (v3.0.1) and Preact (v8.3.1)? In React there is a ReactElement<T>
for that. Is there something similar in Preact?
I have a menu
component, which can only have menuItem
child components. How can I enforce that in Preact with TypeScript? With React I could do something like:
interface Props {
children?: React.ReactElement<MenuItem>[] | React.ReactElement<MenuItem>;
}
I know that that ReactElement
is implemented in preact-compat
, but I don't want to use it.
Thank you for any advice!
Now the simplest option is probably the ComponentChildren
type (see this commit: https://github.com/preactjs/preact/commit/cd422d047f6d21607ff980c84b9c4ac1845ca798). For example:
import { h } from "preact";
import type { ComponentChildren } from "preact";
type Props = {
children: ComponentChildren;
}
export function ComponentWithChildren(props: Props) {
return (
<div>
{props.children}
</div>
);
}