Ts-morph: Adding type to param of non-parenthesized arrow function throws error

Created on 24 Jul 2018  路  4Comments  路  Source: dsherret/ts-morph

Now this one might be a bit of a challenge...

I tried to add a type annotation to a parameter of an arrow function where the arrow's single parameter is not surrounded by parenthesis:

myArg => console.log( myArg );

Here's my reproduction of the error:

import Project, { ArrowFunction, SyntaxKind } from 'ts-simple-ast';

const project = new Project();
const sourceFile = project.createSourceFile( 'my-file.ts', `
    myArg => console.log( myArg );
` );


const arrowFunction = sourceFile
    .getDescendantsOfKind( SyntaxKind.ArrowFunction )[ 0 ] as ArrowFunction;

const arrowParam = arrowFunction.getParameters()[ 0 ];
arrowParam.setType( 'any' );

Which results in:

Error: Error replacing tree! Perhaps a syntax error was inserted (Current: ExpressionStatement -- New: LabeledStatement).
-- Details --
Path: my-file.ts
Text: "\n\tmyArg: any => console.log( myArg );\n"

I think it may be ending up with this output text after the replacement:

myArg: any => console.log( myArg );

Rather than:

(myArg: any) => console.log( myArg );
bug

Most helpful comment

Very nice, thanks man! Nice implementation too :smile:

Appreciate it!

All 4 comments

Nice, I like this bug! It shows the benefit of the library and how it can abstract away these problems. I'll fix this tomorrow evening.

Hehe, sounds good! And yes, that is a good call and a huge benefit of ts-simple-ast!

Thanks for taking a look :)

Hey @gregjacobs, this is fixed in 12.7.2. Also fixed for setInitializer and setHasQuestionToken.

Let me know if you run into or think of any more scenarios. Thanks!

Very nice, thanks man! Nice implementation too :smile:

Appreciate it!

Was this page helpful?
0 / 5 - 0 ratings