如何通过ts-morph获取TypeScript变量的可用属性与方法?
如何用ts-morph分析
Graph变量的类型属性与方法 你需要通过ts-morph调用底层TypeScript类型检查能力,而不是仅停留在变量声明节点的表层操作——VSCode能展示类型信息,本质也是调用了TypeScript的类型检查器,ts-morph完全可以实现同样的效果。
具体实现步骤如下:
获取变量的类型符号
先定位到Graph的变量声明节点,再通过getType()和getSymbol()获取其类型符号,这是访问属性、方法的核心入口:import { Project } from "ts-morph"; const project = new Project(); const sourceFile = project.addSourceFileAtPath("你的目标文件路径.ts"); // 获取Graph变量声明 const graphVar = sourceFile.getVariableDeclaration("Graph"); if (!graphVar) throw new Error("未找到Graph变量"); // 获取变量对应的类型与类型符号 const graphType = graphVar.getType(); const graphSymbol = graphType.getSymbol(); if (!graphSymbol) throw new Error("无法获取Graph的类型符号");遍历所有属性与方法
通过类型符号的getMembers()方法拿到所有成员,再区分属性和方法:// 遍历Graph的所有成员 const members = graphSymbol.getMembers(); members.forEach(member => { const memberName = member.getName(); // 判断是否为可调用的方法 const isMethod = member.getType().getCallSignatures().length > 0; console.log(`${memberName}: ${isMethod ? "方法" : "属性"}`); // 若为方法,可进一步获取参数、返回值信息 if (isMethod) { member.getType().getCallSignatures().forEach(sig => { const params = sig.getParameters().map(p => `${p.getName()}: ${p.getType().getText()}`).join(", "); const returnType = sig.getReturnType().getText(); console.log(` 签名: (${params}) => ${returnType}`); }); } });处理继承与混合类型
由于Graph是extend(EmptyGraph, stdLib)生成的混合类型,可通过getBaseTypes()获取父类型,递归遍历父类成员:// 遍历Graph的基类型成员 const baseTypes = graphType.getBaseTypes(); baseTypes.forEach(baseType => { const baseSymbol = baseType.getSymbol(); if (baseSymbol) { console.log("\n基类型成员:"); baseSymbol.getMembers().forEach(member => console.log(`- ${member.getName()}`)); } });
需要注意,要确保ts-morph的项目配置能正确解析G6的类型定义(比如正确引入依赖、配置tsconfig),否则可能无法完整获取类型信息。
内容的提问来源于stack exchange,提问作者qg_java_17137
相关产品推荐
相关产品推荐

