Monday, May 20, 2024
117
rated 0 times [  124] [ 7]  / answers: 1 / hits: 39591  / 6 Years ago, mon, may 21, 2018, 12:00:00

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?


More From » ecmascript-6

 Answers
35

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 imported with import type { Foo } from ..., since there is no value named Foo



  1. 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.


[#54387] Thursday, May 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;