The issue does not lie within Preact itself, but rather with how TypeScript handles JSX/TSX. Enforcing a specific type for children is challenging since they can be of any type - string, number, boolean, etc.
However, there is a solution. You can define that a component should accept any component as the 'children' prop, as long as it meets certain requirements using the generic interface VNode<T>
. Here's an example:
import { VNode } from 'preact';
interface ChildProps {
itemTitle: string;
}
function Child(props: ChildProps) {
return (
<div>Children</div>
);
}
export interface ParentProps {
children: VNode<ChildProps> | VNode<ChildProps>[];
}
function Parent(props: ParentProps) {
return (
<div>
{props.children}
</div>
)
}
function App() {
return (
<Parent>
<Child itemTitle='Child 1' />
<Child itemTitle='Child 2' />
</Parent>
);
}
The only drawback here is that if you introduce another component like Child2
with similar props to Child1
, TypeScript will accept it without issues.