我们有一些复杂的组件组成,而我很难使它们成为类型安全的。根据下面的代码,我希望Typescript能够为Menu.Item
或Menu.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>
</>
}
结果:
答案 0 :(得分:0)
问题出在菜单类型定义上:
React.FC<{}, MenuSubComponents>
正确用法是:
React.FC<MenuSubComponents>
您可以在此处看到此操作:https://codesandbox.io/s/condescending-lamarr-xjkcw