Is there a point to doing 'import type' rather than 'import' with Flow?

James Ko picture James Ko · May 21, 2018 · Viewed 7.7k times · Source

Flow allows you to use the following syntax to import types:

// SomeClass.js
export default class SomeClass {}

// SomeFile.js
import type SomeClass from './SomeClass';

What's the benefit of using import type instead of import? Does it tell Flow more information and let it perform better static analysis?

Answer

loganfsmyth picture loganfsmyth · May 21, 2018

For the specific case of classes, it is either example will work. The key thing is that it breaks down like this:

  • import type ... from imports a Flow type
  • import ... from imports a standard JS value, and the type of that value.

A JS class produces a value, but Flowtype also interprets a class declaration as a type declaration, so it is both.

So where is import type important?

  1. If the thing you're importing doesn't have a value, using a value import will in some cases be interpreted as an error, because most JS tooling doesn't know that Flow exists.
    • export type Foo = { prop: number }; for instance can only be important with import type { Foo } from ..., since there is no value named Foo
  2. If the thing you're importing has a JS value, but all you want is the type
    • Importing only the type can make code more readable, because it is clear from the imports that only the type is used, so nothing in the file could for instance, create a new instance of that class.
    • Sometimes importing only the type will allow you to avoid dependency cycles in your files. Depending on how code is written, it can sometimes matter what order things are imported in. Since import type ... only influences typechecking, and not runtime behavior, you can import a type without actually requiring the imported file to execute, avoiding potential cycles.