定义对象时的Typescript对象属性

时间:2019-01-31 15:12:37

标签: reactjs typescript

我正在尝试在创建对象的过程中推断对象属性。我有以下界面。

interface Config {
  comp: ComponentType<any>;
  props: any;
}

我可以成功创建一个配置。

const config: Config = {
  comp: MyComponent;
  props: {
    prop1: 3,
    prop2: "test"
  }
};

我将如何强制props对象使用组件本身中定义的props?

const config: Config[] = [
  {
    comp: MyComponent,
    props: {
      prop1: 3,
      prop2: "test"
    }
  },
  {
    comp: AnotherComponent,
    props: {
      anotherProp: false
    }
  }
];

然后我如何对每个配置可以具有不同组件的数组强制执行相同的规则?

我尝试使用泛型和infer关键字,但是很难使它起作用。

谢谢。

编辑:

在最后一个示例中,我希望将 const config 输入为元组,并且看起来像这样:

[
  {
     comp: MyComponent,
     props: ExtractPropsTypeOf<MyComponent>
  },
  {
     comp: AnotherComponent,
     props: ExtractPropsTypeOf<AnotherComponent>
  }
]

1 个答案:

答案 0 :(得分:1)

以下是React希望如何接收打字道具的一个示例:

export interface CaptionProps {
  children: string;
}

export interface CaptionState {
}

export default class Caption extends React.Component<CaptionProps, CaptionState> {
  constructor(props: Readonly<CaptionProps>) {
    super(props);
  }

  render(): React.ReactNode {
    return <div className="caption">{ this.props.children }</div>;
  }
}

如果您这样声明组件,则应该能够使用以下语法:

interface Config<Props> {
  comp: React.Component<Props, any>;
  props: Props;
}
相关问题