How to change the state with React TypeScript 2.0?

Viewed 6346

For such a small component created by React and TypeScript.

interface Props {
}

interface State {
  isOpen: boolean;
}

class App extends React.Component<Props, State> {

  constructor(props: Props) {
    super(props);
    this.state = { 
      isOpen: false
    };
  }

  private someHandler() {
    // I just want to turn on the flag. but compiler error occurs.
    this.state.isOpen = true;
    this.setState(this.state);
  }

}

When I tried to upgrade TypeScript 1.8 to 2.0, then I got the compiler error like below.

error TS2540: Cannot assign to 'isOpen' because it is a constant or a read-only property.

I guess maybe it caused by this change.

so I just want to turn on the flag.

What should I do? Does anyone know the workaround?

Thanks.

update

the quick workaround is just doing like the below.

this.setState({ isOpen: true });
3 Answers

As you are using a class based component, setting the state with setState() method will merge the isOpen property to the existing state. So this will work:

this.setState({isOpen: true});
Related