如何使用ts-morph将导入类型解析为其实际定义
用ts-morph直接获取外部导入类型的方法
不用正则解析路径,ts-morph借助TypeScript的符号系统就能直接拿到外部导入类型的原始声明:
- 先通过变量声明的
getType()获取类型,再调用getSymbol()拿到类型对应的符号对象 - 调用符号的
getDeclarations()方法,就能获取到该类型在源文件中的原始声明节点(比如SomeInterface的接口定义)
示例代码:
import { SyntaxKind, InterfaceDeclaration } from "ts-morph"; // 假设已获取到目标sourceFile const myVariableDecl = sourceFile.getVariableDeclarationOrThrow("myVariable"); const typeSymbol = myVariableDecl.getType().getSymbol(); if (typeSymbol) { // 筛选出接口类型的声明节点 const interfaceDecl = typeSymbol.getDeclarations().find( decl => decl.isKind(SyntaxKind.InterfaceDeclaration) ) as InterfaceDeclaration; // 直接获取接口的名称、属性等信息 console.log(interfaceDecl.getName()); // 输出 "SomeInterface" interfaceDecl.getProperties().forEach(prop => { console.log(`属性: ${prop.getName()},类型: ${prop.getType().getText()}`); }); }
如果遇到类型别名的场景,还可以用type.getAliasSymbol()获取原始符号,再通过同样方式拿到声明节点。
内容的提问来源于stack exchange,提问作者Ruben
相关产品推荐
相关产品推荐

