Home > front end >  Is there a way to identify a declaration statement using the Compiler API?
Is there a way to identify a declaration statement using the Compiler API?

Time:11-02

I'm using the Compiler API to search for some structures written (majorly) in JavaScript. Is there any way to infer whether a variable declaration is using a const (or const assertions), var or let statement? For example, in this code:

const a = 1;

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. I'm using Typescript 4.4.3.

CodePudding user response:

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.

That's exactly how you do this. Make sure to check the flags using 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
  • Related