1

I have a class that I have several properties declared on this in the constructor.

class DevModuleLookup {
  constructor() {
    this.kGlobal = 'z'
    this.kHelpMessage = '...'
  }

  ...
}

I get a flow error

property `kGlobal`. Property not found in DevModuleLookup

I could use class properties but they are still stage 2 ATM and I cannot use them until they reach stage 3.

Any suggestions?

JeffBaumgardt
  • 1,378
  • 3
  • 16
  • 24
  • I _think_ even with those flags off, you can do `kGlobal: string;` in the class body? You just can't assign a value, e.g. `kGlobal: string = 'z';`. I can't verify myself at the moment. – loganfsmyth Jul 12 '17 at 19:09
  • I'd like to stay with stage 3 and above. Class properties are still stage 2. – JeffBaumgardt Jul 12 '17 at 20:28
  • 1
    Assigning values to the properties in the class body is stage 3, but putting properties with type annotations in in the class body is just Flow, the same way `: number` anywhere else is just Flow. – loganfsmyth Jul 12 '17 at 21:08
  • For some reason my webpack build keeps failing on me yelling at me for the missing transform for class properties. The dev server runs just fine though. – JeffBaumgardt Jul 12 '17 at 21:09
  • You'll want to install and activate the `flow` preset for Babel, sounds like you haven't done that. So it does typecheck when you add them to the class body though? – loganfsmyth Jul 12 '17 at 21:51
  • Yeah I do have that. I wonder if the production build isn't capturing it. Is there a way to see the webpack.config output. We build out webpack config at run time. – JeffBaumgardt Jul 12 '17 at 21:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149054/discussion-between-jeff-and-loganfsmyth). – JeffBaumgardt Jul 12 '17 at 22:04

1 Answers1

3

For your code to typecheck, you'll need to declare the types in the class body, e.g.

class DevModuleLookup {
  kGlobal: string;
  kHelpMessage: string;

  constructor() {
    this.kGlobal = 'z'
    this.kHelpMessage = '...'
  }
}

Flow has adopted part of the proposed class property syntax for ES classes, by allowing properties to be named in the class body.

Even if you don't want to use class properties themselves, since they are a proposal and not part of the official language, you can still use the annotations above without the = ... assignment, and they will just be stripped out the same way any other Flow type annotation will be removed by Babel (assuming you have enabled the flow preset).

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • As an addition to this answer the ordering of babel presets is important. Presets are last to first where I had preset-env second in order and it was throwing the error in webpack build. - https://stackoverflow.com/questions/38620375/does-the-order-of-babel-6-presets-matter – JeffBaumgardt Jul 12 '17 at 22:30