如何使用 Preact 和 TypeScript 对组件子组件进行类型检查?

Rob*_*bin 7 typescript reactjs preact

是否可以使用 TypeScript (v3.0.1) 和 Preact (v8.3.1) 对组件子组件进行类型检查?在 React 中有一个ReactElement<T>可以做到这一点。Preact中有类似的东西吗?

我有一个menu组件,它只能有menuItem子组件。如何在 Preact 中使用 TypeScript 强制执行此操作?使用 React 我可以做类似的事情:

interface Props {
    children?: React.ReactElement<MenuItem>[] | React.ReactElement<MenuItem>;
}
Run Code Online (Sandbox Code Playgroud)

我知道这ReactElement是在 中实现的preact-compat,但我不想使用它。

谢谢您的任何建议!

Mat*_*iuk 11

现在最简单的选择可能是ComponentChildren类型(请参阅此提交: https: //github.com/preactjs/preact/commit/cd422d047f6d21607ff980c84b9c4ac1845ca798)。例如:

import { h } from "preact";

import type { ComponentChildren } from "preact";

type Props = {
  children: ComponentChildren;
}

export function ComponentWithChildren(props: Props) {
  return (
    <div>
      {props.children}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)