【发布时间】:2020-02-11 07:07:35
【问题描述】:
试图创建一个动态的 React 组件。根据所选组件有条件地传递正确 propType 的正确方法是什么。到目前为止,这是我在<SelectComponent {...props.props} /> 这一行上遇到的错误,因为道具与组件不匹配:
export interface SidebarProps {
type: keyof typeof components,
props: AddEditJobsProps | AddEditCustomersProps
}
const components = {
job: AddEditJobs,
customer: AddEditCustomers
};
export default function Sidebar(props: SidebarProps) {
const { open, toggle } = useToggle();
const SelectComponent = components[props.type];
return (
<RightSidebar open={open} toggleDrawer={toggle}>
<SelectComponent {...props.props} />
</RightSidebar>
);
}
编辑: 将 any 添加到 props 可修复错误,但 Typescript 将无法匹配所选的 type 与相应的 props 在类型检查期间这是我希望在这里完成的。
export interface SidebarProps {
type: keyof typeof components,
props: AddEditJobsProps | AddEditCustomersProps | any
}
【问题讨论】:
-
所以
SelectComponent可以是AddEditJobs或AddEditCustomers,具体取决于props.type的值? -
你想要的行为是什么?你只是想摆脱错误吗?或者你想让 Typescript 真正推断出
props.props的类型?前者可能是可能的,但后者是不可能的,因为SelectComponent的实际类型在运行时之前是未知的,并且不能被 Typescript 推断。 -
@jered 好问题,我不关心运行时,我想要的行为是在编码期间从打字稿中获得良好的反馈,所以当我将“类型”传递给我的动态侧边栏组件时,我得到看看我还需要通过什么“道具”。
标签: javascript reactjs typescript