AleksG
AleksG

Reputation: 370

Flowtype – how to export and import types?

I've followed https://flow.org/en/docs/install/, and flow is working fine when used in single files, like this:

 // @flow 

type NumberAlias = number;

const n: NumberAlias = "123";

Flow will correctly point out that:

  5: const n: NumberAlias = "123";
                            ^^^^^ string. This type is incompatible with
  5: const n: NumberAlias = "123";
              ^^^^^^^^^^^ number

The problem arises when I try to export a type from moduleA and import that type in moduleB:

(moduleA.js)

// @flow 

export type NumberAlias = number;

(moduleB.js)

// @flow

import type { NumberAlias } from './moduleA';

const n: NumberAlias = 123;

Flow complains:

src/moduleB.js:3
  3: import type { NumberAlias } from './moduleA';
                                      ^^^^^^^^^^^ ./moduleA. Required module not found

Isn't this exactly how it's described in https://flow.org/en/docs/types/modules/?

Folder structure is:

src/
    moduleA.js
    moduleB.js
.flowconfig
package.json

Upvotes: 9

Views: 1409

Answers (2)

Mike Patrick
Mike Patrick

Reputation: 11006

This worked as you'd expect when I set it up, using the two files provided sitting in a src folder under my project's root. moduleB.js:

Flow error

If I fail to put // @flow in Module A, the compiler treats NumberAlias as any, and fails to complain. I initially forgot to add it, and this threw me for a few minutes.

The only way I could find to produce the "moduleA not found" error was to change the file extension (or file name) for moduleA. For example, if the file is called moduleA.ts, ModuleA.js, or simply moduleA, the import will fail to resolve as above.


Incidentally, both

import type { NumberAlias } from './moduleA';

and

import type { NumberAlias } from './moduleA.js';

resolve just fine in my local environment. You might try the second format?


Provided these conditions are met:

  • Both files live in the same folder
  • Both have a .js (or .jsx) extension
  • The filenames match the import statements exactly
  • Both contain the // @flow comment

The code you provided works using Flow 0.57.3 with Node 8.7.0. In light of the error message, I'd suggest triple checking the filenames and extensions especially.

Upvotes: 2

Taras Yaremkiv
Taras Yaremkiv

Reputation: 3600

As a workaround, one can put all types into file anyname.js and put it into flow-typed directory. Then all the types would be exported automaticaly, without import.

Upvotes: 1

Related Questions