dsherret / ts-morph

TypeScript Compiler API wrapper for static analysis and programmatic code changes.
https://ts-morph.com
MIT License
4.98k stars 195 forks source link

Inserting a comment after the last child of an object literal expression using insertProperty, should not add trailing comma #961

Open dsherret opened 3 years ago

dsherret commented 3 years ago

Describe the bug

Version: 10.0.2

To Reproduce

import { Project, ts } from "ts-morph";

const project = new Project({ useInMemoryFileSystem: true });
const sourceFile = project.createSourceFile("src/file.ts", `const o = {\n    p1: 5\n};`);
const objectLiteralExpression = sourceFile.getVariableDeclarationOrThrow("o")
    .getInitializerIfKindOrThrow(SyntaxKind.ObjectLiteralExpression);

const prop = objectLiteralExpression.getPropertyOrThrow("p1");
objectLiteralExpression.insertProperty(prop.getChildIndex() + 1, "// 1");
expect(sourceFile.getFullText()).to.equal(`const o = {\n    p1: 5\n    // 1\n};`);

Expected behavior

Should not add a trailing comma, but it does.

brandongregoryscott commented 2 years ago

Hey @dsherret - I stumbled upon this issue when trying to debug some manipulations I'm trying to do for another project. I think this bug is also happening with EnumDeclaration nodes. I set up a CodeSandbox with an example: https://codesandbox.io/s/ts-morph-961-enum-trailing-comma-2kkg3?file=/src/create-enum.ts