Is there code generation API for TypeScript?
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({});
constr.setBodyText('this.myProp = myProp');
classDeclaration.addProperty({
name: 'myProp',
type: 'string',
initializer: 'hello world!',
scope: Scope.Public
});
sourceFile.formatText();
console.log(sourceFile.getText());
Is there something simmilar for typescript
Not yet, but the TypeScript team is opening up the emitter (what is that) for plugins that would make this a supported scenario : https://github.com/Microsoft/TypeScript/issues/5595
as of Oct-2018 You could use standard TypeScript API for that
import ts = require("typescript");
function makeFactorialFunction() {
const functionName = ts.factory.createIdentifier("factorial");
const paramName = ts.factory.createIdentifier("n");
const parameter = ts.factory.createParameterDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*dotDotDotToken*/ undefined,
paramName
);
const condition = ts.factory.createBinaryExpression(
paramName,
ts.SyntaxKind.LessThanEqualsToken,
ts.factory.createNumericLiteral(1)
);
const ifBody = ts.factory.createBlock(
[ts.factory.createReturnStatement(ts.factory.createNumericLiteral(1))],
/*multiline*/ true
);
const decrementedArg = ts.factory.createBinaryExpression(
paramName,
ts.SyntaxKind.MinusToken,
ts.factory.createNumericLiteral(1)
);
const recurse = ts.factory.createBinaryExpression(
paramName,
ts.SyntaxKind.AsteriskToken,
ts.factory.createCallExpression(functionName, /*typeArgs*/ undefined, [decrementedArg])
);
const statements = [ts.factory.createIfStatement(condition, ifBody), ts.factory.createReturnStatement(recurse)];
return ts.factory.createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ [ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
/*asteriskToken*/ undefined,
functionName,
/*typeParameters*/ undefined,
[parameter],
/*returnType*/ ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),
ts.factory.createBlock(statements, /*multiline*/ true)
);
}
const resultFile = ts.createSourceFile(
"someFileName.ts",
"",
ts.ScriptTarget.Latest,
/*setParentNodes*/ false,
ts.ScriptKind.TS
);
const printer = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed
});
const result = printer.printNode(
ts.EmitHint.Unspecified,
makeFactorialFunction(),
resultFile
);
console.log(result);
Taken here: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#user-content-creating-and-printing-a-typescript-ast