如何在AST中获取变量类型?求识别globalThis类型变量的方法
解决方案:识别AST中类型为globalThis的变量
先把两个核心问题拆解清楚:
- 纯JavaScript AST本身不带类型信息,所以获取变量类型要么靠语法/作用域推导,要么依赖TypeScript这类类型检查工具
- 识别
globalThis类型的变量,可结合「作用域静态分析」或「类型检查器」两种路径实现,下面分别给出具体方案
一、思路1:作用域静态分析(无需额外类型工具)
针对你的示例代码const foo = () => { const baz = this; },箭头函数的this是词法绑定的——它会直接继承外层作用域的this。如果外层是全局作用域,这个this就指向globalThis,自然baz的类型就是globalThis。
修改后的jscodeshift实现
module.exports = (fileInfo, api, options) => { const j = api.jscodeshift; const root = j(fileInfo.source); // 定位所有赋值为this的变量声明 root.find(j.VariableDeclarator, { init: { type: 'ThisExpression' } }).forEach(declaratorPath => { const varName = declaratorPath.node.id.name; const outerFunction = declaratorPath.parentPath.parentPath; // 先判断外层是不是箭头函数(箭头函数才会词法绑定this) if (outerFunction.node.type === 'ArrowFunctionExpression') { // 向上遍历作用域,确认最终是否到全局作用域 let currentScope = outerFunction.scope; while (currentScope.parent) { currentScope = currentScope.parent; } // 如果最终落在全局作用域,说明this指向globalThis if (currentScope.type === 'global') { console.log(`变量${varName}的类型为globalThis`); } } }); return root.toSource(); };
二、思路2:TypeScript类型检查(复杂场景更准确)
如果要处理非全局作用域的this指向、类型别名等复杂情况,就得借助TypeScript的Compiler API来获取精准类型。你可以在astexplorer里直接切换到TypeScript parser,或者结合ts-morph工具实现。
核心步骤
- 在
astexplorer顶部的Parser下拉框选择TypeScript,生成的AST会包含类型相关元信息 - 通过TypeScript API查询变量类型,判断是否匹配
globalThis
简化示例(结合ts-morph)
import { Project } from 'ts-morph'; const project = new Project(); const sourceFile = project.addSourceFileAtPath('你的目标文件.js'); // 找到变量baz的声明节点 const bazDecl = sourceFile.getVariableDeclaration('baz'); if (bazDecl) { const varType = bazDecl.getType(); // 直接判断类型文本是否匹配globalThis if (varType.getText() === 'typeof globalThis') { console.log('变量baz的类型为globalThis'); } }
astexplorer实用技巧
- 切换到TypeScript parser后,右侧AST面板会显示类型注解相关节点,方便你直观查看类型信息
- 利用右侧的
Scope面板,可以快速遍历节点的作用域层级,验证箭头函数的this绑定关系
内容的提问来源于stack exchange,提问作者Jon Sud
相关产品推荐
相关产品推荐

