facebook / jscodeshift

A JavaScript codemod toolkit.
https://jscodeshift.com
MIT License
9.22k stars 477 forks source link

Creates syntax error when transforming Flow types without identifier #361

Open silvenon opened 4 years ago

silvenon commented 4 years ago

In certain cases jscodeshift causes a syntax error when transforming types (in my case Flow, but maybe TS, too). Seee this demo.

Transform:

export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  return root
    .find(j.StringTypeAnnotation)
    .replaceWith(j.numberTypeAnnotation())
    .toSource()
}

export const parser = 'flow'

Source:

type Ob = {
  [string]: number,
}

Result:

type Ob = {
  [: number]: number,
}
silvenon commented 4 years ago

That extra colon was probably supposed to be an identifier, but I can't figure out why jscodeshift is adding it. I expected the same bug to happen when I replace it with the node of the same type:

return root
    .find(j.StringTypeAnnotation)
    .replaceWith(j.stringTypeAnnotation())
    .toSource()

But it works fine.

silvenon commented 4 years ago

Also, I just found out that the codemod transforms this:

export type Foo = string

into:

export type type Foo = number

Notice the extra type. 😓This only happens within the export declaration, type Foo = string would be transformed correctly.

Maybe this is all related somehow.