Search code examples
javascriptecmascript-6flowtypeflow-typed

Extract flow type annotations into external files


I would like to strip the verbosity of Flow out of my source code. Is there a way to declare the types in a separate file?

This is what I have:

// @flow
// src/writer.js
class Writer {
  write(text: string):string {
    return `I wrote ${text}`
  }
}

This is what I'm trying to achieve:

// @flow
// src/writer.js
class Writer {
  write(text) {
    return `I wrote ${text}`
  }
}

// src/definitions/writer.js.flow
declare class Writer {
  write(text: string):string
}

I tried placing writer.js.flow in the flow-typed folder and I also tried declaring a IWriter interface that Writer would extend. Flow doesn't like it.

I'm not sure if this is even possible, because functions can declare their own variables which should be properly annotated too.


Solution

  • There is not a way to do exactly what you want in Flow. There are a few specific use-cases that are supported:

    • If you have some non-Flow code (like maybe a library) and some Flow application code, and you want it to be possible for the Flow code to use the non-Flow code but know what types are involved, you can write a "library definition" for the untyped code. It's important to understand that this library definition isn't checked against the implementing code, it's just assumed to be true, so you have to be careful writing libdefs.

    • If you have Flow code and you want to read or run it without the Flow annotations, you can use flow-remove-types to strip the Flow syntax out of the files.

    But I think you want something else. It sounds like you want to write code without Flow annotations, then write the annotations in another file, but have Flow check the annotations against the code. This is not something Flow currently supports.

    (As an aside, it's also not something I expect they would add. The major benefit of types is as an aid when reading, writing, and thinking about code. Flow has good inference, so overall you don't have to write that many types out. But the ones you do (as in exported functions) are generally helpful to thinking about the code.)