Khan/flow-to-ts

SyntaxError for Flow named type imports inside braces

jtbandes opened this issue · 7 comments

I think this may be a problem only with the --prettier option.

Interesting. Turning off prettier in the playground makes the error go away.

It looks like import {type Foo} from "baz" is not valid TypeScript. I tried it in their playground and it complains about a missing comma. Moving type outside the braces fixes the issue.

If type has to be outside the braces it means that mixed imports like import {A, type B} form "c" will need to be split.

@kevinbarabash, by split, do you mean that import {A, type B} from "c" would need to become:

import { A } from "c"
import type { B } from "c"

For anyone looking for a workaround until this is fixed, I used a small ruby script as a pre-processing step to split up the types in the project I was converting. This covered our cases, but doesn't cover all possible ways that types could have been imported in Flow.

require 'find'

Find.find('src') do |path|
  unless FileTest.file?(path) && File.basename(path).match?(/\.jsx?$/)
    next
  end

  output = File.read(path)
    .lines
    .map do |line|
      if line.match?(/^import (?!type ).*\btype (.*) from ['"].*['"]$/)
        type_free_import = line.gsub(/type [^, ]+(?:, | as [^, ]+)?/, '')
          .sub(/[, ]+\}/, ' }')
          .sub(/,? *\{ +\}/, '')
          .sub(/import +from ["'].+["']\n/, '')

        types = line.scan(/type ([^, ]+(?: as [^, ]+)?)/)
        types_import = "import type { #{types.join(', ')} }" + line.sub(/.+ from /, ' from ')

        type_free_import + types_import
      else
        line
      end
    end
    .join

  File.write(path, output)
end

Apparently this syntax is now supported in TypeScript 4.5: https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/