Created
August 20, 2020 13:14
-
-
Save roytouw7/8410bfb63125a55945795cd39b53de87 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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