如何从 ts.TypeObject 中获取类型名称和成员 TypeObjects?

How can I get type names and member TypeObjects from a ts.TypeObject?

我正在使用 TypeScript 编译器来执行一些代码生成。这是我第一次直接使用编译器 API。

下面有一些丑陋的缩小(改进我将保存到另一个问题),我能够从 FirstStatement 得到 ts.TypeObject。但是,我不确定如何使用此对象来检查其类型。

我需要能够用这种类型的对象(或其他)做两件事:

  1. 提取顶级类型名称。
  2. 递归地将成员的类型名称提取为基元。
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
            }
        })
    }
});

我该怎么做?或者,至少,我应该在文档中的什么地方查找此类问题?

我想我写这篇文章的时候感觉有点太懒了。 docs.

中有一个例子