问题描述
我正在尝试利用最近添加的对儿童输入的支持在 TypeScript 编译器和 @types/react 中,但很挣扎.我使用的是 TypeScript 2.3.4 版.
I'm trying to take advantage of the recently added support for typing of children in the TypeScript compiler and @types/react, but struggling. I'm using TypeScript version 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>
}
}
当我尝试像这样使用这些组件时:
When I try to use these components like so:
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[]
,尽管这是我使用的唯一子元素类型.
It seems to be inferring the type of children as just Element[]
instead of Tab[]
even though that's the only type of children I'm using.
限制 children props 的接口而不是直接限制子组件的类型也可以,因为我需要做的就是从子组件.
It would also be fine to restrict the interface of the children props instead of restricting the type of the children components directly, since all I need to do is pull some specific props out of the children components.
推荐答案
Edit 2: 原来这种方法可以防止警告,但根据评论 TabProps
没有正确检查.
Edit 2: Turns out that this approach prevent the warning, but according to the comments TabProps
aren't properly checked.
您应该尝试像这样设置界面 TabbedViewProps 的子项
You should try to set children of interface TabbedViewProps like so
interface TabbedViewProps { children?: React.ReactElement<TabProps>[] }
这里的想法不是告诉你的 TabbedView
有一个 Tab
的数组,而是告诉你的 TabbedView
他有一个 Tab
的数组code>element 需要特定的道具.在你的情况下TabProps
.
The idea here is not to tell your TabbedView
has an array of Tab
, but instead tell your TabbedView
he has an array of element
which takes specific props. In your case TabProps
.
编辑(感谢 Matei):
Edit ( thx to Matei ):
interface TabbedViewProps {
children?: React.ReactElement<TabProps>[] | React.ReactElement<TabProps>
}
这篇关于如何使用 TypeScript 2.3 中新增的支持来限制 TypeScript 中 React Children 的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!