Skip to content

Instantly share code, notes, and snippets.

@zakhenry
Created April 19, 2020 18:02
Show Gist options
  • Save zakhenry/7c4d0f2616bf8ba6d7a86b515b492973 to your computer and use it in GitHub Desktop.
Save zakhenry/7c4d0f2616bf8ba6d7a86b515b492973 to your computer and use it in GitHub Desktop.
Typescript enum codegen
import * as ts from 'typescript';
function makeEnum() {
return ts.createEnumDeclaration(
undefined,
[ts.createToken(ts.SyntaxKind.ExportKeyword), ts.createToken(ts.SyntaxKind.DeclareKeyword)],
'Direction',
[
ts.createEnumMember('UNKNOWN', ts.createLiteral(0)),
ts.createEnumMember('NORTH'),
ts.createEnumMember('SOUTH'),
ts.createEnumMember('EAST'),
ts.createEnumMember('WEST'),
],
);
}
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, makeEnum(), resultFile);
console.log(result);
@zakhenry
Copy link
Author

zakhenry commented May 1, 2020

use https://ts-creator.js.org/ to help write this builder code next time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment