You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:00:55