如何将TypeScript推断类型转换为JSON或JavaScript对象?
需求描述
现有如下TypeScript文件:
// my-ts-file.ts const inner = { hello: "world", }; export const value = { prop1: "hello", prop2: "world", prop3: 42, prop4: inner, }
在VS Code中悬停查看时,TypeScript已正确推断出value变量的类型:
const value: { prop1: string; prop2: string; prop3: number; prop4: { hello: string; }; }
现需编写独立程序读取该文件,将导出的const value的推断类型转换为如下格式的JSON:
{ "prop1": "string", "prop2": "string", "prop3": "number", "prop4": { "hello": "string" } }
请问该需求是否可行?应如何实现?可使用哪些库或工具包?
解答
可行性
完全可行。TypeScript本身提供了用于类型分析的原生API,能直接获取变量的推断类型,再将其转换为目标JSON格式。
实现步骤
- 解析TS文件:通过TypeScript相关工具加载目标文件,构建可分析的程序实例与类型检查器。
- 定位目标变量:遍历文件的导出符号,精准找到名为
value的导出常量。 - 提取类型信息:借助类型检查器获取该变量的推断类型,递归解析类型结构(包含对象属性、嵌套对象等层级关系)。
- 转换为JSON结构:将解析后的类型映射为键值对形式的JSON对象,属性名对应原类型的属性,属性值为类型的字符串描述(如
"string"、"number")。 - 输出JSON:将转换后的对象序列化为格式化的JSON字符串。
可用工具与库
- TypeScript Compiler API:无需额外安装,直接使用项目中的
typescript包即可,核心用于类型解析与检查。 - ts-morph:基于TypeScript Compiler API封装的工具库,提供更简洁的API来遍历、操作TS代码和类型,降低开发复杂度。
- @typescript-eslint/typescript-estree:ESLint的TS解析器,可用于解析TS抽象语法树,配合类型检查器获取类型信息。
简单实现示例(基于ts-morph)
import { Project, VariableDeclarationKind } from "ts-morph"; async function generateTypeJson(filePath: string) { // 创建ts-morph项目实例 const project = new Project(); // 添加目标文件 const sourceFile = project.addSourceFileAtPath(filePath); // 找到导出的const value const valueDeclaration = sourceFile.getVariableDeclaration("value"); if (!valueDeclaration || valueDeclaration.getDeclarationKind() !== VariableDeclarationKind.Const) { throw new Error("未找到导出的const value"); } // 获取变量的类型 const type = valueDeclaration.getType(); // 递归转换类型为JSON结构 const typeJson = convertTypeToJson(type); // 输出格式化后的JSON console.log(JSON.stringify(typeJson, null, 4)); } function convertTypeToJson(type: any): any { // 处理对象类型 if (type.isObject()) { const properties = type.getProperties(); const result: Record<string, any> = {}; for (const prop of properties) { const propType = prop.getTypeAtLocation(prop.getValueDeclarationOrThrow()); result[prop.getName()] = convertTypeToJson(propType); } return result; } // 处理基础类型 return type.getText(); } // 调用示例 generateTypeJson("./my-ts-file.ts");
内容的提问来源于stack exchange,提问作者01101010
相关产品推荐
相关产品推荐

