Skip to content

Instantly share code, notes, and snippets.

@roytouw7
Created August 20, 2020 13:14
Show Gist options
  • Save roytouw7/8410bfb63125a55945795cd39b53de87 to your computer and use it in GitHub Desktop.
Save roytouw7/8410bfb63125a55945795cd39b53de87 to your computer and use it in GitHub Desktop.
import * as ts from 'typescript';
const printer = ts.createPrinter();
// Create ts.Node from given typescript code.
export const createNode = <T extends ts.Node>(code: string, type: number): [T, ts.SourceFile] => {
const sourcefile = ts.createSourceFile('test.ts', code, ts.ScriptTarget.ES2015, true);
const node = fetchNodeFromSourceFile(sourcefile);
if (node.kind !== type) {
throw new Error(`TypeScript node created from given code doesn't match expected type, expected: ${type} but compiled: ${node.kind}!`);
}
return [node as T, sourcefile];
};
// Get string representation of given TypeScript node.
export const printNode = <T extends ts.Node>(node: T, sourceFile: ts.SourceFile): string => {
return printer.printNode(ts.EmitHint.Expression, node, sourceFile);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment