动态反作用组件上的动态Typescript道具



问题是,我有一组组件

const EquationOptions = (props: Equation) => { … }
const GridOptions = (props: Grid) => { … }
const OptionGroupOptions = (props: OptionGroup) => { … }
const PageOptions = (props: Page) => { … }
const SectionOptions = (props: Section) => { … }
const TableOptions = (props: Table) => { … }
const containerOptions = {
Equation: EquationOptions,
Grid: GridOptions,
"Option Group": OptionGroupOptions,
Page: PageOptions,
Section: SectionOptions,
Table: TableOptions,
};

我正在尝试动态设置组件,如下所示:

if (activeComponent) {
const ComponentOptions = containerOptions[activeComponent?.componentType];
options = <ComponentOptions {...activeComponent} />;
}

其中activeComponent变量的类型为:

type ContainerModels = Equation | Grid | OptionGroup | Page | Section | Table;

编辑器在ComponentOptions标签上不断显示错误:

类型"{variables:string[];equipment:string;componentType:"equipment"|"Grid"|"Option Group"|"Page"|"Section"|"Table"。。。还有4个…|{…;}"不可分配给类型"IntrnsicAttributes&方程式&网格&选项组&页面&章节&表'。类型"{variables:string[];equation:string;componentType:"equation"|"Grid"|"Option Group"|&quotquot;Page"|"Section"|"Table"quot;uid:string;formComponentType:formComponentType;identifier:string;caption:string,hint:string;}"在类型"Grid"中缺少以下属性:templateRows,templateColumns

虽然这个程序之所以有效,是因为它总是在标签中传递正确的道具类型,但我不知道如何让typescript推断我传递的道具的类型。

我只通过给containerOptions:一个正确的类型就解决了这个问题

interface ContainerOptions {
[key: string]: Function;
}
export const containerOptions: ContainerOptions = {
Equation: EquationOptions,
Grid: GridOptions,
"Option Group": OptionGroupOptions,
Page: PageOptions,
Section: SectionOptions,
Table: TableOptions,
};

最新更新