Last active
October 14, 2019 07:29
-
-
Save hasparus/b1f78bffb783376a62dcd666de41da60 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 sourceFile = ts.createSourceFile( | |
"example.ts", | |
` | |
interface Host { | |
/** | |
* @mockType {internet.ipv6} | |
*/ | |
addr: string; | |
foo: { | |
bar: number; | |
qux: { | |
/** | |
* @mockType {internet.ipv4} | |
*/ | |
addr2: string; | |
} | |
}; | |
}`, | |
ts.ScriptTarget.ESNext, | |
false, | |
ts.ScriptKind.TS | |
); | |
const visit = <T>(n: ts.Node, f: (n: ts.Node) => T[]): T[] => { | |
const results = f(n); | |
n.forEachChild(n => { | |
results.push(...visit(n, f)); | |
}); | |
return results.filter(Boolean); | |
}; | |
interface PropertySignatureWithJSDoc extends ts.PropertySignature { | |
jsDoc: ts.JSDoc[]; | |
} | |
const collectMockTypes = (n: ts.Node) => { | |
if (n.kind === ts.SyntaxKind.PropertySignature && 'jsDoc' in n) { | |
const propertySignature = n as PropertySignatureWithJSDoc; | |
return propertySignature.jsDoc.flatMap(doc => { | |
if (doc.tags) { | |
return doc.tags | |
.filter(tag => tag.tagName.text === "mockType") | |
.map(tag => { | |
return { | |
name: propertySignature.name.getText(sourceFile), | |
mockType: tag.comment, | |
}; | |
}); | |
} | |
return []; | |
}); | |
} | |
return []; | |
}; | |
console.log(visit(sourceFile, collectMockTypes)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment