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

如何获取TypeScript文件元数据,自动生成Lambda调用客户端?

解决方案:TypeScript元数据提取工具推荐

直接给你几个无需正则、能精准提取TS文件函数元数据的工具:

  • TypeScript Compiler API:TS官方原生工具,可直接解析代码的抽象语法树(AST),能获取函数名称、导出状态、输入输出类型等信息。你可以编写脚本,用ts.createProgram加载handler文件,遍历AST节点定位导出函数,再从节点的type属性解析类型细节。

  • ts-morph:基于TS Compiler API封装的上层库,语法更简洁易用。它允许你以对象操作的方式访问TS代码结构,比如直接调用getFunctions()筛选导出函数,再通过getParameters()、getReturnType()快速获取类型信息,无需手动遍历AST节点。

  • @typescript-eslint/utils:如果项目已使用ESLint,可复用其TS解析器,通过该工具的AST能力提取元数据。它的API与TS Compiler API兼容,且能和ESLint生态无缝整合,适合已有ESLint配置的项目。

简单示例(基于ts-morph)

假设你有如下handler.ts文件:

export async function hello(event: { name: string }): Promise<{ message: string }> {
  return { message: `Hello ${event.name}` };
}

用ts-morph编写的提取脚本:

import { Project } from 'ts-morph';

const project = new Project();
const sourceFile = project.addSourceFileAtPath('./handler.ts');

// 获取所有导出的函数
const exportedFunctions = sourceFile.getFunctions().filter(func => func.isExported());

exportedFunctions.forEach(func => {
  const funcName = func.getName();
  const paramType = func.getParameters()[0]?.getType()?.getText();
  const returnType = func.getReturnType().getText();
  
  console.log(`函数名:${funcName}`);
  console.log(`输入类型:${paramType}`);
  console.log(`输出类型:${returnType}`);
});

通过这类脚本提取到元数据后,你就能自动生成带类型的Lambda调用客户端代码或类型定义文件,彻底省去手动重复定义的繁琐操作。

内容的提问来源于stack exchange,提问作者TalesMGodois

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:05:56