codemix / babel-plugin-typecheck

Static and runtime type checking for JavaScript in the form of a Babel plugin.
MIT License
886 stars 44 forks source link

[Question] React PropTypes support #75

Closed nkbt closed 8 years ago

nkbt commented 8 years ago

I acknowledge this might be out of scope for babel-plugin-typecheck but what about React PropTypes?

I would expect following example to fail static type check.

const Component = React.createClass({
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  render() {
    return <div>{this.props.name}</div>;
  }
});

const App = React.createClass({
  render() {
    return <Component name={42} />;
  }
});

Could you please give some insight on if/how it is possible do static check for react components (runtime check is performed by React itself though)?

The reason to have a static check is to be able to deal with higher kind of types. Sort of (well, syntax could be different for correct static type checks):

const Name = React.PropTypes.string;
const User = React.PropTypes.shapeOf({
  name: Name.isRequired
});

const Component = React.createClass({
  propTypes: {
    user: User.isRequired
  },
  render() {
    return <div>{this.props.user.name}</div>;
  }
});

const App = React.createClass({
  render() {
    var user = {name: 'Test'};
    // I suppose this to fail since plain Object is not type of User
    return <Component user={user} />;
  }
});

PS: feel free to close the ticket if it is really out of scope.

phpnode commented 8 years ago

We can do it if all declarations are in the same file, but in practice that's very rare. Issue is that unlike normal types, we can't sensibly communicate the property types across module boundaries.

nkbt commented 8 years ago

Thanks. Any suggestion on if it possible to do static+runtime checks for react component props? Not necessarily with PropTypes, but in any other way.

phpnode commented 8 years ago

@nkbt it's something that really relies on whole-of-program analysis, which is something I'd like to do in future but won't have time to do for a while. I don't think there's a good way to do it at the moment.

nkbt commented 8 years ago

No problem :+1: