Flow: How to fix errors for function binding

Created on 20 Sep 2016  Â·  4Comments  Â·  Source: facebook/flow

With the following code I get an error that I would like to fix:

/* @flow weak */

class MyClass {
    thisUsesThis() {
        console.log(this);
    }

    constructor() {
        this.thisUsesThis = this.thisUsesThis.bind(this);
    }
}

This is the error:

node_modules/.bin/flow check                                                                                                                                                                    4722ms  di 20 sep 2016 17:07:48 CEST
static/js/modules/stream-react/test.js:9
  9:         this.thisUsesThis = this.thisUsesThis.bind(this);
             ^^^^^^^^^^^^^^^^^ assignment of property `thisUsesThis`
  9:         this.thisUsesThis = this.thisUsesThis.bind(this);
                  ^^^^^^^^^^^^ property `thisUsesThis`. Property not found in
  3: class MyClass {
           ^^^^^^^ MyClass


Found 1 error

I understand that it is complaining because I'm assigning to a property that is actually a method. How do I change my code to make this error disappear?

Most helpful comment

You have to declare it as property like this:

class MyClass {
    thisUsesThis: () => void;

    thisUsesThis() {
    }

    constructor() {
        this.thisUsesThis = this.thisUsesThis.bind(this);
    }
}

All 4 comments

You have to declare it as property like this:

class MyClass {
    thisUsesThis: () => void;

    thisUsesThis() {
    }

    constructor() {
        this.thisUsesThis = this.thisUsesThis.bind(this);
    }
}

Thanks that indeed works. Is it correct that this should cause errors in weak mode?

Yep @vkurchatkin has the answer 😊

Methods are readonly by default.

Hi team - hope you are all well. I've been declaring my methods as mentioned above but noticed that I am not getting errors. Not sure if I should be getting errors. Please see the contrived example at example

The above doesn't report an error. Should it?

or do I also need to at types to the function:

handleOnClick(arg: Example): void {
  return arg + 3
}

Seems a bit redundant, but curious if that is the best practice?

Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bennoleslie picture bennoleslie  Â·  3Comments

jamiebuilds picture jamiebuilds  Â·  3Comments

ctrlplusb picture ctrlplusb  Â·  3Comments

ghost picture ghost  Â·  3Comments

philikon picture philikon  Â·  3Comments