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?
import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there's no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript's output.
The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.
The exported type can be imported by using a named import as import {Person} from './another-file' . You can have as many named exports as necessary in a single file. Here is an example of exporting a type from a file called another-file. ts .
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 typeimport ... 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?
export type Foo = { prop: number };
for instance can only be imported with import type { Foo } from ...
, since there is no value named Foo
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.As stated at this link
With import type, you want to import the type of the class and not really the class itself.
An example given at the same link as below
// @flow
// Post-transformation lint error: Unused variable 'URI'
import URI from "URI";
// But if you delete the require you get a Flow error:
// identifier URI - Unknown global name
module.exports = function(x: URI): URI {
return x;
}
Due to we imported URI
into this component, linter
will check if we have used the class in this component. However, we only using it as a flow type checking and hence linter
will throwing an error saying we imported unused variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With