首页 > 解决方案 > 定义对象时的打字稿对象属性

问题描述

我试图在创建对象期间推断对象属性。我有以下界面。

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>
  }
]

标签: reactjstypescript

解决方案


以下是 React 期望接收类型化 props 的示例:

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;
}

推荐阅读