Search code examples
reactjstypescriptcomponents

Not allowed to point to this.state.anything at any time


I can set the state with the function setState I can also declare it in the contructor.

that's it.

typescript does not allow me to access it no matter where I put it I need to access it in my methods and in my html but this.state.mything give the error :

TS2339: Property 'mything' does not exist on type 'Readonly{}>'.

what do I do?

there are no such examples online. everyone uses this.state.mything without a hitch seemingly.

class Component extends React.Component {

  constructor(props: any) {
     super(props);
     this.state = { mything: ''} 
  }

  render() {
      return(
         <div>
            {this.state.mything} //ERROR
         </div>
      )
  }

Solution

  • in this case the state has to be instantiated like so, for good measure this applies to props as well so here is how you instantiate props and state

    interface Props {
        mything: string
    }
    
    interface State {
        mything: string
    }
    
    class Component extends React.Component<Props, State> {
    
      constructor(props: any) {
         super(props);
         this.state = { mything: ''} 
      }
    
      render() {
          return(
             <div>
               {this.state.mything}
             </div>
    
          )
      }