Cannot assign to 'state' because it is a constant or a read-only property

Before rolling back (as suggested by @torvin's answer), please read through https://github.com/DefinitelyTyped/DefinitelyTyped/pull/26813#issuecomment-400795486.

This was not meant to be a regression - the solution is to use state as a property. It is better than previous approach (setting state in a constructor) because:

  • you don't need constructor at all anymore
  • you can't forget to initialize state (it is now a compile-time error)

For example:

type Props {}

type State {
  active: boolean
}

export default class Square extends React.Component<Props, State> {
  public readonly state: State = {
    active: false
  }

  public render() {
    //...
  }
}

Another approach:

type Props {}

const InitialState = {
  active: false
}

type State = typeof InitialState

export default class Square extends React.Component<Props, State> {
  public readonly state = InitialState

  public render() {
    //...
  }
}

This appears to be a recent change in @types/react introduced in commit 542f3c0 which doesn't work very well, considering the fact that Typescript doesn't support assigning parent's readonly fields in derived constructors.

I suggest rolling back to a previous version of @types/react. Version 16.4.2 appears to be the last one before the unfortunate change has been made.

You can pin the version by removing the ^ in your package.json:

"devDependencies": {
  ...
  "@types/react": "16.4.2",

Also check out the discussion about this change on DefinitelyTyped github pull request page