Hi there! This is my first try to use ts-simple-ast. We would like to convert certain interfaces to types. But in some cases "trailing" comments are removed and we don't know why.
Given the following example:
{
"name": "ts-ast-test",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "ts-node index.ts"
},
"dependencies": {
"ts-simple-ast": "^11.2.1"
},
"devDependencies": {
"ts-node": "^6.0.5"
}
}
import Project, { TypeAliasDeclarationStructure } from 'ts-simple-ast';
const project = new Project();
const example = `interface Foo {
foo: string;
}
// foo
const foo = 1;`;
const file = project.createSourceFile('example.ts', example);
const interfaces = file.getInterfaces();
interfaces.forEach((myInterface) => {
const typeAlias: TypeAliasDeclarationStructure = {
name: myInterface.getName(),
type:
'{' +
myInterface.getMembers().map(p => p.getText()).join(' ') +
'}'
};
file.insertTypeAlias(myInterface.getChildIndex(), typeAlias);
myInterface.remove();
});
console.log(file.getText());
The output is this:
type Foo = {foo: string;};
const foo = 1;
As you can see the comment // foo was removed. I wonder why? When I paste the same example to https://astexplorer.net/ with TypeScript selected as the parser it shows that the comment is not a trailing comment of interface Foo, but a leading comment to const foo = 1;.
So is this a bug that the comment will be removed when myInterface.remove(); is called?
Thank you.
Hi @donaldpipowitch, yes this is a bug and thanks for reporting this! That comment is not owned by the interface. In the beginning of this library comments were an afterthought so there are still a few areas like this that aren't correct.
@dsherret - just in case, this is the difference between ts.Node getText vs getFullText - and the same for other methods like getStart() getFullStart() getFullWidth(), etc - if internally the library use "Full" methods instead of non full then those trailing comments (tribia content as they call it) will be considered. - if not it will be discarded. My two cents.
@cancerberoSgx thanks, but no it's not related to that. I fixed a similar issue to this before so I'll have this fixed soon.
Fixed in 11.2.2. Let me know if you run into any other issues.
This is awesome. I'll test it. Thank you _very_ much for the quick fix and the release.
Most helpful comment
This is awesome. I'll test it. Thank you _very_ much for the quick fix and the release.