最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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
}

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
}
Share Improve this question edited Aug 24, 2017 at 9:09 Val asked Aug 24, 2017 at 8:42 ValVal 22.8k11 gold badges71 silver badges87 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

You have to declare your toggle as Function in your class like this (pact 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).

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 = () => {
    ...
}

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./ryyppy/flow-guide/issues/6

and

https://github./facebook/flow/issues/3076

EDIT

From the official document you need to do like this to avoid error:

Convariant property inpatible with contravariant use in assignment of property

function g(o: {-p: string}): void {
  o.p = "default";
}
var o: {p: ?string} = {p: null};
g(o);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论