dsherret / ts-morph

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

MethodDeclarationStructure with isGenerator: true does not serialize with the asterisk #1501

Closed ajvincent closed 9 months ago

ajvincent commented 9 months ago

Describe the bug

Version: 21.0.1

To Reproduce

import { Project } from "ts-morph";

const project = new Project();
const sourceFile = project.createSourceFile("test.ts", {
  statements: [
    {
      kind: StructureKind.Function,
      name: "foo",
      isGenerator: true,
      returnType: "IterableIterator<number>",
      statements: ["yield 1;", "yield 2;"],
    },
    {
      kind: StructureKind.Class,
      name: "MyClass",
      methods: [
        {
          kind: StructureKind.Method,
          name: "foo",
          isGenerator: true,
          returnType: "IterableIterator<number>",
          statements: ["yield 1;", "yield 2;"],
        }
      ]
    }
  ]
});

console.log(sourceFile.print());

Expected behavior

function* foo(): IterableIterator<number> {
    yield 1;
    yield 2;
}
class MyClass {
    * foo(): IterableIterator<number> {
        yield 1;
        yield 2;
    }
}

Actual behavior

function* foo(): IterableIterator<number> {
    yield 1;
    yield 2;
}
class MyClass {
    foo(): IterableIterator<number> {
        yield 1;
        yield 2;
    }
}

Note the missing asterisk before the foo() method.

ajvincent commented 9 months ago

I think the fix goes in MethodDeclarationStructurePrinter.ts. Probably we just need to copy one line from FunctionDeclarationStructurePrinter.ts

ajvincent commented 9 months ago

I've tested this locally and I believe it will work. I'm going to attempt a fix for this bug, per CONTRIBUTING.md. This specific fix is probably trivial, but I want to add some tests too.