我正在尝试利用 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/