代码之家  ›  专栏  ›  技术社区  ›  shaan

如何声明this.someProperty以响应typeScript?

  •  0
  • shaan  · 技术社区  · 5 年前

    嗨,我要 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
            }
    
    
        }
    

    这个。某物 这样我就不会得到typecript错误。

    2 回复  |  直到 5 年前
        1
  •  1
  •   Madara's Ghost    5 年前

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

    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
    }
    
        2
  •  -1
  •   Trupti Shetty    5 年前

    你可以试着用任何的。