Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type definitions from imported files not marked with @flow

TL;DR How do I tell flow to import type definitions from imported modules not declared with @flow?

Longer version

Flow seams to be able to derive types from files not using the flow syntax (see example).

Example file 'flow.js'

if(Math.random() < 0.5) {
  var y = "hello";
} else {
  var y = 2;
}

var i = y;

Command 'flow suggest flow.js'

if(Math.random() < 0.5) {
-  var y = "hello";
+  var y: number | string = "hello";
 } else {
-  var y = 2;
+  var y: number | string = 2;
 }
-var i = y;
+var i: number | string = y;

It also seam to be able to list all imports from a specific file using flow get-importers. The tools seams to be there but I can't figure out how to automatically tell flow to get the type definitions from my imports not declared with @flow.

I would like it to traverse down the import chain, calculate the types and use them in files marked with @flow. I do not want it type check code not marked with @flow, only retrieve the types.

like image 363
Linus Oleander Avatar asked Aug 05 '16 13:08

Linus Oleander


1 Answers

I reword your question to what I believe you mean.

How do I create type definitions for files that Flow does not know about?

There's two things:

  • If the file is owned by you (i.e. not a third party lib inside node_modules or such), then you can create a *.js.flow file next to it that documents its exports.
  • If the file is not owned by you (i.e. third party lib inside node_modules or such), then you can create a libdef file inside flow-typed/name-of-library.js

For .js.flow files you write the definitions like this:

// @flow
declare module.exports: { ... }

For libdef files you write the definitions like this:

declare module "my-third-party-library" {
  declare module.exports: { ... }
}

Hopefully that answers your question

like image 73
James Kyle Avatar answered Nov 19 '22 15:11

James Kyle