reactjs - 如何使用 TypeScript 2.3 中新增的支持来限制 TypeScript 中 React Children 的类型?

标签 reactjs typescript

我正在尝试利用 recently added support for typing of children在 TypeScript 编译器和@types/react 中,但很挣扎。我使用的是 TypeScript 版本 2.3.4。

假设我有这样的代码:

interface TabbedViewProps {children?: Tab[]}
export class TabbedView extends React.Component<TabbedViewProps, undefined> {

  render(): JSX.Element {
    return <div>TabbedView</div>;
  }
}

interface TabProps {name: string}
export class Tab extends React.Component<TabProps, undefined> {
  render(): JSX.Element {
    return <div>Tab</div>
  }
}

当我尝试像这样使用这些组件时:

return <TabbedView>
  <Tab name="Creatures">
    <div>Creatures!</div>
  </Tab>
  <Tab name="Combat">
    <div>Combat!</div>
  </Tab>
</TabbedView>;

我得到如下错误:

ERROR in ./src/typescript/PlayerView.tsx
(27,12): error TS2322: Type '{ children: Element[]; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<TabbedView> & Readonly<{ children?: ReactNode; }> ...'.
  Type '{ children: Element[]; }' is not assignable to type 'Readonly<TabbedViewProps>'.
    Types of property 'children' are incompatible.
      Type 'Element[]' is not assignable to type 'Tab[] | undefined'.
        Type 'Element[]' is not assignable to type 'Tab[]'.
          Type 'Element' is not assignable to type 'Tab'.
            Property 'render' is missing in type 'Element'.

它似乎将子项的类型推断为 Element[] 而不是 Tab[],尽管那是我使用的唯一子项类型。

编辑:限制 children props 的接口(interface)也可以,而不是直接限制子组件的类型,因为我需要做的就是从子组件。

最佳答案

编辑 2:原来这种方法阻止了警告,但根据评论 TabProps 未正确检查。

您应该尝试像这样设置接口(interface) TabbedViewProps 的子级

interface TabbedViewProps { children?: React.ReactElement<TabProps>[] }

这里的想法不是告诉你的TabbedView有一个Tab的数组,而是告诉你的TabbedView他有一个的数组code>element 需要特定的 Prop 。在您的情况下 TabProps

编辑(感谢 Matei):

interface TabbedViewProps {
    children?: React.ReactElement<TabProps>[] | React.ReactElement<TabProps>
}

关于reactjs - 如何使用 TypeScript 2.3 中新增的支持来限制 TypeScript 中 React Children 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44475309/

相关文章:

javascript - 使用 axios 将数据发送到输入 ReactJS 中的每个更改

reactjs - 测试自定义 Hook 并收到“警告 : An update to TestHook inside a test was not wrapped in act

reactjs - 在 Next.js next-auth 的 session 中保存 jwt accessToken 是否安全?然后使用 useSession Hook 在客户端访问它?

javascript - React 是否有可能修改引用?

class - Typescript 中类型为 'class' 的变量

javascript - 如何将对象数组转换为在 typescript 中具有动态键的单个对象

javascript - 通过 npm 安装 d3.js 对 Angular 2 TypeScript 项目有什么好处吗?

javascript - 根据焦点输入显示元素

Angular Route Start 和 Route End 事件

javascript - 如何将 NgStyle 与条件函数一起使用?