Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flowtype bind cause error `Convariant property incompatible with contravariant use in assignment of property`

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:

enter image description here

What can I do to pass flow test?

toggle can be any function even empty.

toggle() {
    /// do nothing
}
like image 584
Val Avatar asked Aug 24 '17 08:08

Val


3 Answers

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

like image 53
Adrien Lacroix Avatar answered Nov 15 '22 21:11

Adrien Lacroix


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).

1. Cast this as any

Reference to flowtype issue #1517.

(this: any).toggle = this.toggle.bind(this);

2. Assign to another variable of 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);

3. define function type clearly

toggle: Function;
toggle() {
    ...
}

4. define function with type + arrow function

toggle: Function = () => {
    ...
}
like image 23
Val Avatar answered Nov 15 '22 23:11

Val


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);
like image 39
Jigar Shah Avatar answered Nov 15 '22 22:11

Jigar Shah