6

I'm playing with Facebook's new Flow Type checking system.

In Flow, meet Underscore it appears that they change this JavaScript code

var root = this;

into this

var root: any = this;

But this is no longer valid JavaScript, right? I understand why external Interface files would be useful, but how are type annotations added directly into valid JavaScript sources?

Previously, Google Closure compiler and other projects used on JS comments.

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
Ozten
  • 188
  • 9
  • Flow parses a superset of JavaScript syntax; the actual code that ends up running in a browser (or wherever) is plain JavaScript. – Pointy Nov 22 '14 at 17:48

3 Answers3

5

As of Flow 0.4.0 you are able to put the Flow syntax into the comments. This solves your issue. So your example would look like:

var root/*: any*/ = this;

This results in valid JavaScript syntax and there is no need to transpile your code.

Further details can be found here: http://flowtype.org/blog/2015/02/20/Flow-Comments.html

Már Örlygsson
  • 14,176
  • 3
  • 42
  • 53
psiphi75
  • 1,985
  • 1
  • 24
  • 36
  • 1
    There's really no good reason not to write all Flow annotations as comments. It transforms flow-typed code from the land of "compiles to JavaScript" to plain old JavaScript that Just Works anywhere. – Már Örlygsson Dec 16 '16 at 14:06
1

You're right, that code is no longer valid javascript. That means that when you use Flow in someJavascriptFile.js, you have to execute a program that removes the Flow code from someJavascriptFile.js, which is called transpiling. Which transpiler to use depends on how you're running javascript, and will probably change over time, so I won't link to any.

You can also wrap the flow types into a comment, eg. var name /*:string*/ = "Hello flow.", which is valid javascript, but makes the code harder to read in my opinion.

In theory, Javascript engines could one day natively support Flow parsing, but that's a long ways off.

Aidan Hoolachan
  • 2,285
  • 1
  • 11
  • 14
0

I missed Running Flow code where it discusses adding a build step to remove type annotations.

You can use the JSX transform tool (part of the React tools) to translate your files to plain JavaScript

I also found flow-typestrip which is alternative.

I like external interface files per module better, as you can avoid introducing a build step.

Ozten
  • 188
  • 9