joarwilk / flowgen

Generate flowtype definition files from TypeScript
Other
657 stars 87 forks source link

Cannot parse `import {type A, type B} from ...` #185

Open stackptr opened 2 years ago

stackptr commented 2 years ago

flowgen does not parse comma-separated type imports correctly. The following diff shows the imports.spec.ts updated with this style of import and the resulting malformed import:

diff --git a/src/__tests__/imports.spec.ts b/src/__tests__/imports.spec.ts
index 3694123..90f5b87 100644
--- a/src/__tests__/imports.spec.ts
+++ b/src/__tests__/imports.spec.ts
@@ -42,6 +42,7 @@ it("should handle type imports", () => {
   const ts = `import type { GeneratorOptions } from "@babel/generator";
 import type traverse from "@babel/traverse";
 import type { Visitor as NewVisitor } from "@babel/traverse";
+import { type Node, type Directive} from "@babel/types";
 `;
   const result = compiler.compileDefinitionString(ts, { quiet: true });
   expect(beautify(result)).toMatchSnapshot();
diff --git a/src/__tests__/__snapshots__/imports.spec.ts.snap b/src/__tests__/__snapshots__/imports.spec.ts.snap
index c0c285e..1372726 100644
--- a/src/__tests__/__snapshots__/imports.spec.ts.snap
+++ b/src/__tests__/__snapshots__/imports.spec.ts.snap
@@ -36,5 +36,6 @@ exports[`should handle type imports 1`] = `
 "import type { GeneratorOptions } from \\"@babel/generator\\";
 import traverse from \\"@babel/traverse\\";
 import type { Visitor as NewVisitor } from \\"@babel/traverse\\";
+import { type, Node, type, Directive } from \\"@babel/types\\";
 "
 `;
stackptr commented 2 years ago

Using the TypeScript AST Viewer shows that in recent versions of typescript (since at least 4.5.5), the type keyword in comma-separated imports does not show up as an ImportSpecifier within NamedImports. However, in the version closest to what is used by flowgen, the AST contains an ImportSpecifier for both type and the named import. The only way I see to distinguish the two is by checking the name.originalKeywordKind, which is ts.SyntaxKind.TypeKeyword. Unfortunately, updating nodes/import.ts to simply filter out these nodes does not do the job... the type keyword needs to be preserved but not treated as an identifier itself.