tscpp
tscpp

Reputation: 1566

Is there a function to print a definition as a string

I want to print the definition/declaration of classes, functions, methods, etc. as a string. Here is an example of how vscode shows the declaration of a class method: (method) TestClass.testMethod(): void, I want to achieve something similar. Now, is there a function for this, or do I need to do I myself by extracting the ast?

The Compiler API or more or less unknown to me, this is my attemps at printing the node. The first code block is input code and the second is the "extractor" code.

I would also appreciate references where I can find more info about this, examples, documentation, anything.

export class TestClass {
    // This is the method declaration node
    testMethod(arg: string) {}
}

const node: ts.MethodDeclaration

checker.typeToString(checker.getTypeAtLocation(node))
// output: (arg: string) => void

printer.printNode(ts.EmitHint.Unspecified, node, sourceFile)
// output: testMethod(arg: string) {}

// wanted: testMethod(arg: string): void

Upvotes: 2

Views: 463

Answers (1)

David Sherret
David Sherret

Reputation: 106660

There might be a better way, but one way is to do get the signature and then call TypeChecker#signatureToString:

const signature = typeChecker.getSignatureFromDeclaration(node);

// outputs: testMethod(arg: string): void
console.log(
  node.name.getText(sourceFile)
  + typeChecker.signatureToString(signature, node)
);

Upvotes: 1

Related Questions