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.
Flow is a static type checker that allows a developer to check for type errors while developing code. This means a developer receives faster feedback about the code, which they can use to improve its quality. Flow works by using annotations and type definitions for adding type checking support to your code.
Type Annotations in Variables and Functions Using type annotations, a developer can explicitly state the type of variable or expression (if it's a string, type, boolean…). They start with colon : followed by the type. Check the following example: let x: string; x = "Using annotations"; Copy.
The type definition syntax of Flow and TypeScript is very similar. They both support JavaScript primitive types and derived types for type checking variables. The type annotations syntax is also very similar in both cases. And they both have generics, which we can use to write code that works with different types.
Both Flow and TypeScript provide the ability to explicitly cast a variable from one type to another. With Flow, we cast using the symbol : , while in TypeScript we cast using the keyword as . // TypeScript let value = 1 as number; // Flow let value = 1; (value: number);
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With