Is there code generation API for TypeScript?

Liero picture Liero · Apr 4, 2016 · Viewed 9.4k times · Source

When I needed to generate some C# code, for example DTO classes from xsd schema, or an excel table, I've used some roslyn API's.

Is there something simmilar for typescript?

[EDIT]: I've end up using ts-morph

Answer

NSjonas picture NSjonas · Sep 10, 2017

Try ts-morph. Only been working with it for about an hour but it seems really capable.

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

const project = new Project();
const sourceFile = project.createSourceFile(`./target/file.ts`);

const classDeclaration = sourceFile.addClass({
    name: 'SomeClass'
});

const constr = classDeclaration.addConstructor({});
const param = constr.addParameter({
  name: 'myProp',
  type: string
});

constr.setBodyText('this.myProp = myProp');

classDeclaration.addProperty({
    name: 'myProp',
    type: 'string',
    initializer: 'hello world!',
    scope: Scope.Public
});
sourceFile.formatText();
console.log(sourceFile.getText());