Flow: Property not found in statics of <class name>

Created on 25 Aug 2017  路  5Comments  路  Source: facebook/flow

How do I add a static method to a class, outside of its definition?

example: flow.org/try/...
The Fantasy Land Specification says to add certain functionality as a static member of the constructor (Semigroup spec). When I try to do this via

class Animal {}
Animal.is_a = is_a  // function 'is_a' defined elsewhere

I get the error:

3: Animal.is_a = is_a
                 ^ property `is_a`. Property not found in
13: Animal.is_a = is_a
    ^ statics of Animal

If I do a property declaration is_a: number => number; there is no change.
If I declare a dummy static function static is_a () {} and then try to overwrite it with Animal.is_a = is_a I get the error:

13: Animal.is_a = is_a
           ^ property `is_a`. Covariant property `is_a` incompatible with contravariant use in
13: Animal.is_a = is_a
    ^ assignment of property `is_a`

I want to be able to add and modify class functionality for code reuse, and to avoid having to wrap objects in a function.

What is the proper way to do this? Any insight is very much appreciated.

Most helpful comment

In Try flow, this works:

function is_a (x) { return x }

class Animal {
  static is_a: number => number
  speak() {
    return "Animal"
  }
}

Animal.is_a = is_a;

const biped = new Animal()

const ans = Animal.is_a(42)

The error you got about static looks like you may be missing a needed babel plugin, maybe class properties transform?

All 5 comments

I also looked at the proposal-class-public-fields.
Section 2.1.1 Static Semantics: IsStatic:
I tried using ClassElement:staticPublicFieldDefinition
is_a: static number => number
it gave me an error saying the static is a reserved word

/*:: is_a: static number => number */
                ^ Use of future reserved word in strict mode

In Try flow, this works:

function is_a (x) { return x }

class Animal {
  static is_a: number => number
  speak() {
    return "Animal"
  }
}

Animal.is_a = is_a;

const biped = new Animal()

const ans = Animal.is_a(42)

The error you got about static looks like you may be missing a needed babel plugin, maybe class properties transform?

That worked, thank you very much. (You can close the issue)
Where can I request that this info be added to the documentation page?https://flow.org/en/docs/types/classes/
Or, should I just submit a pull request to said documentation page?

You're welcome to submit a PR to the doc page (in this repo) or we can change the title/description of this issue to be about adding the docs and I can do it in a little bit.

I'd like to submit the PR. I'll do it as soon as I have a minute in the next 4 hours.

Was this page helpful?
0 / 5 - 0 ratings