首页 文章

如何使用TypeScript 2.3中新添加的支持来限制TypeScript中的React Children的类型?

提问于
浏览
19

我正在尝试利用TypeScript编译器中的recently added support for typing of children和@ 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[] ,即使's the only type of children I' m使用 .

编辑:限制子道具的界面,而不是直接限制子组件的类型也没关系,因为我需要做的就是从子组件中拉出一些特定的道具 .

2 回答

  • -2

    您应该尝试像这样设置接口TabbedViewProps的子项

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

    这里的想法不是告诉你 TabbedView 有一个 Tab 的数组,而是告诉你的 TabbedView 他有一个 element 数组,它需要特定的道具 . 在你的情况下 TabProps .

    编辑(thx到Matei):

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

    在Tab渲染方法中返回的类型是JSX.Element . 这就是导致问题的原因 . TabbedView期待具有Tab类型的子数组 . 我不确定您是否可以将某个组件指定为子类型 . 它可以是字符串或JSX.Element . 你能显示Tab的定义文件吗?

    查看https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react/index.d.ts以了解JSX.Element接口的外观 .

相关问题