How to type check component children with Preact and TypeScript?
Asked Answered
E

2

8

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!

Experimentalism answered 12/8, 2018 at 8:3 Comment(0)
C
12

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>
  );
}
Cork answered 25/11, 2020 at 4:6 Comment(0)
V
3

Preact's equivalent of ReactElement is called VNode (Virtual DOM Node). I'm by no means a TypeScript expert, but I believe your example could work as follows:

interface Props {
    children?: VNode<MenuItem>[] | VNode<MenuItem>;
}

Prior to Preact 8.3.0 I think we relied on JSX.Element instead of VNode.

Virtuosic answered 12/8, 2018 at 17:29 Comment(3)
Thank you for your answer! Well it compiles, but it also compiles, when the children are something else than a MenuItem like a <div>.Experimentalism
Are you using Preact 8.3.0+?Virtuosic
Yes, I'm on "preact": "^8.3.1",.Experimentalism

© 2022 - 2024 — McMap. All rights reserved.