Skip to content

Commit

Permalink
fix: support renaming a property to a private identifier
Browse files Browse the repository at this point in the history
Closes #1198
  • Loading branch information
dsherret committed Oct 30, 2021
1 parent a25c851 commit bf377b6
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ export class StraightReplacementNodeHandler implements NodeHandler {
handleNode(currentNode: Node, newNode: ts.Node, newSourceFile: ts.SourceFile) {
/* istanbul ignore if */
if (currentNode.getKind() !== newNode.kind) {
// support a private identifier and identifier being swapped
const kinds = [currentNode.getKind(), newNode.kind];
if (kinds.includes(ts.SyntaxKind.Identifier) && kinds.includes(ts.SyntaxKind.PrivateIdentifier)) {
currentNode.forget();
return;
}

throw new errors.InvalidOperationError(`Error replacing tree! Perhaps a syntax error was inserted `
+ `(Current: ${currentNode.getKindName()} -- New: ${getSyntaxKindName(newNode.kind)}).`);
}
Expand Down
35 changes: 35 additions & 0 deletions packages/ts-morph/src/tests/issues/1198tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { expect } from "chai";
import { Project } from "../../Project";

describe.only("tests for issue #1198", () => {
it("should not have issues when renaming private identifier", () => {
const project = new Project({ useInMemoryFileSystem: true });
const sourceFile = project.createSourceFile("mod.ts", `class Foo {
private one: string;
private two: string;
}`);
const classDecl = sourceFile.getClasses()[0];
for (const property of classDecl.getInstanceProperties()) {
const name = property.getName();
property.toggleModifier("private", false);
property.rename(`#${name}`);
}

expect(sourceFile.getText()).to.equal(`class Foo {
#one: string;
#two: string;
}`);

// now swap them back
for (const property of classDecl.getInstanceProperties()) {
const name = property.getName().replace(/^#/, "");
property.rename(`${name}`);
property.toggleModifier("private", true);
}

expect(sourceFile.getText()).to.equal(`class Foo {
private one: string;
private two: string;
}`);
});
});

0 comments on commit bf377b6

Please sign in to comment.