This expression is very simple for javascript / react, to bind function with this
scope.
this.toggle = this.toggle.bind(this);
But when introduce with flowtype, that cause error:
What can I do to pass flow test?
toggle can be any function even empty.
toggle() {
/// do nothing
}
You have to declare your toggle
as Function
in your class like this (compact way):
class Foo {
toggle: Function = () {
...
}
}
or, you can separate the signature and the actual method:
class Foo {
toggle: Function;
toggle() {
...
}
}
or, as you say
See this issue for more details
Now I know 4 ways to achieve this.
I knew 1) and 2) before asking the question, but I think that's ugly personally.
Thanks to Adrien Lacroix's solution (of number 3), and lead a way to which I favor the most (number 4).
this
as any
Reference to flowtype issue #1517.
(this: any).toggle = this.toggle.bind(this);
any
Set this
to another variable which is any
type. Same as 1) but with many functions to bind, it's a handy way to avoid casting every line.
const self: any = this;
self.toggle = this.toggle.bind(this);
toggle: Function;
toggle() {
...
}
toggle: Function = () => {
...
}
I think, toggle needs separate declaration, like as below (not sure of use of it as not provided code)
toggle: Function;
toggle() {
console.log('ho');
}
You can check these reference links for the same:
https://github.com/ryyppy/flow-guide/issues/6
and
https://github.com/facebook/flow/issues/3076
EDIT
From the official document you need to do like this to avoid error:
Convariant property incompatible with contravariant use in assignment of property
function g(o: {-p: string}): void {
o.p = "default";
}
var o: {p: ?string} = {p: null};
g(o);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With