简体   繁体   中英

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?

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM