ts-morph icon indicating copy to clipboard operation
ts-morph copied to clipboard

[question] Get thenStatement body text

Open nchanged opened this issue 6 years ago • 6 comments

Hi, here is another question. (Would be nice to start documenting all of that) ;-)

I am doing static computations and I would like to unwrap this statement (replace the original IFStatement with one of those block conditions

if( "a" === "a"){
        console.log("yes");
else {
        console.log("no");
}

node.getThenStatement() gives me a BlockStatement, therefore node.replaceWithText(thenStatement.getText()); adds { and } to the code.

What I am trying to do is, get the child's index and inject the contents, but I haven't found a working solution just yet.

Do you have any idea on how to replace that elegantly?

Thanks

nchanged avatar Jun 03 '19 12:06 nchanged

@nchanged could you post some before/after code that shows what you'd like to do? That way I can ensure I understand what you mean?

Yeah, the thenStatement property in the compiler api is the block. See here: https://ts-ast-viewer.com/

dsherret avatar Jun 03 '19 14:06 dsherret

Yeah, sure. The original code:

const foo = "bar";
if( "a" === "a"){
        console.log("yes");
else {
        console.log("no");
}
const bar = "oi";

after the transformation:

const foo = "bar";
console.log("yes");
const bar = "oi";

nchanged avatar Jun 03 '19 14:06 nchanged

@nchanged hmmm... I should probably add a getBodyText() method to Block (along with setBodyText).

I think for now this workaround should work for you:

node.replaceWithText(thenStatement.getChildSyntaxListOrThrow().getText({ trimLeadingIndentation: true }));

dsherret avatar Jun 03 '19 14:06 dsherret

@dsherret

(property) trimLeadingIndentation: boolean
Argument of type '{ trimLeadingIndentation: boolean; }' is not assignable to parameter of type 'boolean'.ts(2345)

Getting this typing error, and formatting isn't fixed ;-(

nchanged avatar Jun 03 '19 19:06 nchanged

@nchanged What version of ts-morph are you using?

https://github.com/dsherret/ts-morph/blob/9e4f07ddef7def316ed9601b3c78a1409c7aed01/lib/ts-morph.d.ts#L4504

dsherret avatar Jun 03 '19 19:06 dsherret

@dsherret that's better. But how to handle this situation?

if (1 > 2)
          alert(1)
        else
          alert(2)

getChildSyntaxListOrThrow throws an exception...

UPD. @dsherret here is how I solved it. But it's ugly, it would be nice to have in one function in getThenStatement() something like getStatementText() what do you think?

function getStatementText(node: Statement) {
  let theText;
  const syntaxList = node.getChildSyntaxList();
  if (syntaxList) {
    theText = syntaxList.getText({ trimLeadingIndentation: true });
  } else if (node.compilerNode['expression']) {
    theText = node.compilerNode['expression'].getText();
  }
  return theText;
}

nchanged avatar Jun 04 '19 06:06 nchanged