Skip to content

JSX/TSX: Proper way to use State types #3868

Closed
@mikemorton

Description

@mikemorton

Consider this example:

class ToggleState {
    open:boolean
}
class AnimationDemo extends React.Component<{}, ToggleState>
{
  state:ToggleState;
  constructor () {
    super()
    this.state = {open : false, fdsa: 'asdf'};
  }
  getInitialState():ToggleState {
    return {open: false};
  }
  handleMouseDown() {
    this.setState({open: !this.state.open, fdsa: 'asdf'});
  }
  render() {
    return (
      <div>something</div>
    );
  }
};

There doesn't seem to be any guarding against assigning bad values in the state property or passing them into setState.

Note that if I attempt to return something invalid from getInitialState it fails correctly, however React doesn't respect getInitialState unless the component is created with React.createClass(). (See the example here: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#es6-classes)

So is it possible for me ensure that the state property and setState are guarded correctly?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions