在Typescript中反应子组件

时间:2019-07-09 12:43:05

标签: reactjs typescript

我们有一些复杂的组件组成,而我很难使它们成为类型安全的。根据下面的代码,我希望Typescript能够为Menu.ItemMenu.Link提供类型,但是由于某些原因,它没有被推断为“任何”(当您将其包装在JSX中时会被精简为JSX.Element<any>。为什么会这样?

import * as React from 'react';

type RootFunctionComponent<OwnProps, SubComponents> = React.FunctionComponent<OwnProps> & SubComponents;

interface ItemProps {
    text: string;
};

interface LinkProps {
    href: string;
}

const Item: React.FunctionComponent<ItemProps> = props => <div {...props} />;
const Link: React.FunctionComponent<LinkProps> = props => <div {...props} />;

interface MenuSubComponents {
    Item: React.FunctionComponent<;
    Link: typeof Link;
}

const Menu: React.FunctionComponent<{}, MenuSubComponents> & MenuSubComponents = props => <div {...props} />

Menu.Item = Item;
Menu.Link = Link;


const Test: React.FunctionComponent<{}> = () => {
    return <>
        <Menu>
            <Menu.Item text={false} />
            <Menu.Link />
        </Menu>
    </>
}

结果:

the resulting any type

1 个答案:

答案 0 :(得分:0)

问题出在菜单类型定义上:

React.FC<{}, MenuSubComponents>

正确用法是:

React.FC<MenuSubComponents>

您可以在此处看到此操作:https://codesandbox.io/s/condescending-lamarr-xjkcw