如何在与typeScript反应时声明this.someProperty?

时间:2019-05-05 07:53:27

标签: reactjs typescript

嗨,我得到了TS2339: Property 'someProperty ' does not exist on type ''.,我正在尝试向我的react组件this.someProperty添加新属性

    interfaceMyComponentState {
        allClear: boolean;
        data: Array<object>;
    }

    interface MyComponentProps {}

    class MyComponent extends React.Component<MyComponentProps, MyComponentState> {

        constructor(props) {

            super(props);
            this.state = {
                allClear: false,
                data: []
            };
            this.someProperty = []; // this is not a prop nor a state
        }


    }

如何声明this.someProperty,以免出现类型错误。

2 个答案:

答案 0 :(得分:1)

您必须首先将其定义为类属性。

class MyComponent extends ... {
  // string[] so that TypeScript doesn't automatically infer never[] or any[].
  // change string[] to whatever your actual type for someProperty is.
  private someProperty: string[] = [];
  public state = { allClear: false, data: [] };

  // no need for the constructor if all you do is set properties/state
}

答案 1 :(得分:-1)

您可以尝试使用任何一种。

someProperty:any