Martin Mlostek
Martin Mlostek

Reputation: 2970

How to specify this in an object literal with flow in js

I am using // @flow strict but somehow it does not work properly in an object literal when using this. this seemed to be interpreted as any.

This is the example code

type TestType = {
  arr: Array<number>,
  fun: () => void,
}

const testObject: TestType = {
  arr:[],
  fun(){
    this.arr.toUpperCase();
  }
}

testObject.fun();

How can I tell flow that it knows that this.arr.toUpperCase() is not existing, because this.arr is an Array?

Upvotes: 1

Views: 56

Answers (1)

Sasha
Sasha

Reputation: 5944

There seems to no way to explicitly define this type in function:

In Flow you don’t type annotate this and Flow will check whatever context you call the function with.

As a workaround you can do something like::

const testObject: TestType = {
  arr:[],
  fun(){
    const {arr}: TestType = this;
    arr.toUpperCase();
  }
}

testObject.fun(); 

Upvotes: 1

Related Questions