|Written by Ian Elliot
|Thursday, 20 November 2014
The problem with type inference is that it can be very difficult to work out the type of a variable at any given point in the program without actually running it and even then it is possible for the type to change with each run of the program.
Flow does its best, however, to infer the type of any variable and flags errors that it finds. You don't have to type check an entire program as the Flow program will only check files that start with /*@flow*/.
For example, if you have the program
then Flow will notice that the input parameter x has to be a number for the call to work and generates:
The problem is that this sort of type inference quickly starts to run into difficulties caused by ambiguous code. So, in addition, Flow lets you add type annotations. For example:
This makes it easier to type check and you can make things more sophisticated by not only type checking base types but nested class types. Some of the ways that Flow uses type annotations go beyond a simple class hierarchy, e.g. it tries to account for properties that are dynamically added to objects.
For example, Flow will detect a null value and complain if you try to use it in a way that would generate a runtime error. If, however, you add an if statement that checks for a null before using the variable, Flow knows that the code is safe.
Flow does seem to perform useful checks on your code even without type annotation, but there is a warning in the documentation:
"Making existing code typecheck with Flow is not for the faint of heart - and often it may not be worth the effort in the short term. If your project just depends on a library, check out our guide on using Flow with external dependencies. Flow supports interface files so you can use libraries in a typed way without having to run Flow on them at all.
Why is typechecking existing code so hard? Libraries not written with types in mind often contain complex, highly dynamic code that confuses analyses such as Flow."
If you find that you are swamped by type errors when you check your code the advice is to run Flow on a less strict setting.
Flow is used by Facebook in production settings, but it is also very much a work in progress. You can help out on GitHub with improving the code and there are plans to make it better in the future by adding:
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: firstname.lastname@example.org
|Last Updated ( Thursday, 20 November 2014 )