有没有办法使用编译器 API 来识别变量声明类型?

Is there a way to identify a variable declaration kind using the Compiler API?

我正在使用编译器 API 来搜索(主要)在 JavaScript 中编写的一些结构。有什么方法可以推断变量声明是否使用 const(或 const 断言)、varlet 语句?例如,在这段代码中:

const a = 1;

使用 AST Explorer 时,我可以在 VariableDeclarationList 节点中看到值为 2flags 属性,但是当我使用编译器 [=24= 进行解析时] 这个 属性 假设一个不同的值。我试图将 flags 属性 与 ts.NodeFlags.Const 进行比较,但结果总是错误的。我正在使用 Typescript 4.4.3.

I can see a flags property with value 2 inside the VariableDeclarationList node when using AST Explorer but when I'm parsing using the Compiler API this property assumes a different value. I tried to compare the flags property with ts.NodeFlags.Const but it always results in false.

这正是您的做法。确保使用 bitwise operators:

检查标志
const sourceFile = ts.createSourceFile("file.ts", "const a = 1;");
const varStmt = sourceFile.statements[0] as ts.VariableStatement;
const isConst = (varStmt.declarationList.flags & ts.NodeFlags.Const) !== 0;

console.log(isConst); // true