[flow] Improve covariant style
We currently follow an awkward style for covariants
constructor() {
super();
const self: any = this;
self.closeConditionalPanel = this.closeConditionalPanel.bind(this);
self.onEscape = this.onEscape.bind(this);
self.onGutterClick = this.onGutterClick.bind(this);
self.onGutterContextMenu = this.onGutterContextMenu.bind(this);
self.onScroll = this.onScroll.bind(this);
self.onSearchAgain = this.onSearchAgain.bind(t
@thejameskyle shared some wisdom on how we can improve the style
Class methods are covariant in Flow by default, which in effect means they are "read-only" and cannot be assigned to.
class Error extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this); // Error
// ^ property `onClick`. Covariant property `onClick` incompatible with contravariant use in
// assignment of property `onClick`
}
onClick(event: ButtonClickEvent) {
// ...
}
render() {
return <button onClick={this.onClick}>Click Me</button>;
}
}
In order to make this work, you need to use an additional class field, which are invariant (read & write) by default, like this:
class WorksWithClassPropertyType extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this); // Works!
}
onClick: (ButtonClickEvent) => void;
onClick(event) {
// ...
}
}
Alternatively you can use the class properties proposal to get around all of this:
class WorksWithClassPropertyArrowFunction extends React.Component {
onClick = (event: ButtonClickEvent) => {
// ...
};
}
is there a reason why we don't use return <button onClick={e => this.onClick(e)}>Click Me</button>; ?
Do you mean, why don't we use JSX? I'd be happy to :)
We were holding off the past couple months to finish up the import/commonjs refactor and keep the codebase stable for launching. Perhaps we start allowing a small amount of JSX nowish and allow bigger refactors post launch, like july?
Ah sorry i wasn't clear enough. I meant why don't we use this shorthand: e => this.onClick(e)
directly where we need the binding? ie)
dom.div({
onClick: e => this.onClick(e)
});
with our current syntax
also, regarding JSX -- I am honestly quite happy with how we are doing it now. It reminds me of hiccup syntax. The only issue is that it might be deprecated...
@codehag Performance is impacted by creating functions within every render() vs creating them once per component.
I was planning to cover thay as part if fixing flow any code style issues this weekend
/claim
Thanks for claiming the issue! :wave:
Here are some link for getting setup, contributing, and development tips. We're always happy to answer questions in slack! If you become busy, feel free to /unclaim it.
:fox_face: Debugger team!
I can continue on with the proposal in my PR if everyone agrees, it should be easy to knock-out a lot of the : any from the code with this change.
closing as we have an approach now