I'm working with a TypeScript compiler to perform some code generation. This is my first time working with the compiler API directly.
With some ugly narrowing below (improvement of which I will save for another question), I'm able to get a ts.TypeObject
from a FirstStatement
. However, I'm unsure how I can use this object to examine its type.
I need to be able to do two things with this type object (or other):
- Extract the top-level type name.
- Recursively extract members' type names down to primitives.
import ts from “typescript”;
// get program, checker, and sources
const program = ts.createProgram([__filename], {});
const checker = program.getTypeChecker();
const sources = program.getSourceFiles();
// iterate through sources
sources.forEach((source)=>{
if(source.fileName === __filename){ // find this file
ts.forEachChild(source, (node)=>{
if(ts.SyntaxKind[node.kind] === "FirstStatement"){ // find first statements
ts.forEachChild(node, (child)=>{
if(!(child as any).declarations) return;
const dec = (child as any).declarations[0]; // get the first declaration
if(dec && dec.symbol) console.log(checker.getTypeOfSymbolAtLocation(dec.symbol, node))
}); // get the type of the symbol
}
})
}
});
How can I do this? Or, in the least, where should I be looking in the docs for these kinds of questions?
I guess I was just feeling a bit too lazy when I wrote this. There is an example in the docs.