Skip to content

Instantly share code, notes, and snippets.

@mvolkmann
Last active May 11, 2017
Embed
What would you like to do?
Flow .js.flow declaration files
const double = require('./math').double;
console.log(double('20'));
function double(n) {
return n * 2;
}
exports.double = double;
// This didn't work for me.
//function double(n: number): number {}
// This didn't work either.
declare export function double(n: number): number;
// Running "flow" in the directory of these files outputs "No errors!"
@jedwards1211
Copy link

jedwards1211 commented May 11, 2017

Okay, you'll need to have // @flow at the top of both demo.js and math.js.flow. Then you'll see

flow
demo.js:5
  5: console.log(double('20'));
                        ^^^^ string. This type is incompatible with the expected param type of
  7: declare export function double(n: number): number;
                                       ^^^^^^ number. See: math.js.flow:7


Found 1 error

Without // @flow at the top of your files flow will report no errors. It might be nice if it said "0 files checked (you need to add @flow to some files)" but unfortunately it doesn't.

When I use flow gen-flow-files math.flow > math.flow.js it generates a file that contains a comment that says The file does not have an @flow at the top!. Of course it doesn't. I'm trying to demonstrate how I can specify types for files that, for whatever reason, I cannot modify.

You can copy math.js temporarily to add @flow at the top so that you can run gen-flow-files on it. But even if you do that you get an error because gen-flow-files only works on files that have flow type annotations:

flow gen-flow-files math.js

math.js:3
  3: function double(n) {
                     ^ parameter `n`. Missing annotation

Found 1 error

I think it would be reasonable for flow to infer that double takes and returns a number since it uses multiplication, but unfortunately it doesn't make that inference. So generally for creating .js.flow files for source files out of your control that don't have type annotations, you'll be best off writing them by hand.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment