TypeScript导入interfaces.ts后types为空,如何遍历接口生成模板?
解决TypeScript接口导入后为空对象的问题
TypeScript接口是编译时类型注解,编译成JavaScript后会被完全移除,所以你在运行时导入types模块,里面根本没有接口的任何信息,自然是空对象。要实现“利用接口属性和类型生成模板”的需求,得把接口的类型信息转化为运行时可访问的数据,下面是几种可行方案:
方案一:用值对象模拟接口结构(简单易上手)
在interfaces.ts中,同时定义运行时可访问的schema对象和基于该对象生成的TypeScript类型,这样既能保留类型检查,又能在运行时拿到结构信息:
// interfaces.ts // 定义运行时可用的schema对象,用类型断言指定属性类型 export const UsersSchema = { name: '' as string, password: '' as string, role: '' as string }; // 基于schema对象生成TypeScript接口类型 export type Users = typeof UsersSchema; // 如果有多个接口,按同样方式定义 export const ProductSchema = { id: 0 as number, name: '' as string, price: 0 as number }; export type Product = typeof ProductSchema;
然后在你的业务代码中导入这些schema对象并遍历:
import * as schemas from './interfaces'; for (const key in schemas) { // 过滤出我们定义的schema对象(避免导入其他无关内容) if (key.endsWith('Schema')) { const schema = schemas[key]; // 调用你的生成函数,接口名可以去掉后缀"Schema" func(schema, key.replace('Schema', ''), outputFilePath); } }
方案二:用TypeScript API解析接口文件(适合批量处理)
如果需要处理大量接口,不想手动维护schema对象,可以直接用TypeScript自带的编译器API解析源码的AST(抽象语法树),提取接口的属性和类型信息:
创建一个Node脚本(比如generate-template.ts):
import * as ts from 'typescript'; import * as fs from 'fs'; import * as path from 'path'; // 定义你的生成函数 function func(properties: Array<{name: string; type: string}>, interfaceName: string, outputFilePath: string) { // 这里写你的模板生成逻辑 console.log(`生成接口${interfaceName}的模板:`, properties); } const filePath = path.resolve(__dirname, './interfaces.ts'); const fileContent = fs.readFileSync(filePath, 'utf-8'); // 创建TypeScript程序实例,解析目标文件 const program = ts.createProgram([filePath], {}); const sourceFile = program.getSourceFile(filePath); // 遍历源码的AST节点,提取接口信息 ts.forEachChild(sourceFile, (node) => { if (ts.isInterfaceDeclaration(node)) { const interfaceName = node.name.getText(); const properties: Array<{name: string; type: string}> = []; node.members.forEach((member) => { if (ts.isPropertySignature(member)) { const propName = member.name.getText(); // 获取属性的类型文本,默认unknown const propType = member.type?.getText() || 'unknown'; properties.push({ name: propName, type: propType }); } }); // 调用生成函数 func(properties, interfaceName, './output.txt'); } });
运行脚本可以用ts-node generate-template.ts,或者先编译成JS再用Node运行。
方案三:用第三方库简化AST解析(更易用)
如果觉得TypeScript原生API太繁琐,可以用ts-morph这个库,它封装了TypeScript的AST操作,代码更简洁:
首先安装依赖:
npm install ts-morph --save-dev
然后编写脚本:
import { Project } from 'ts-morph'; function func(properties: Array<{name: string; type: string}>, interfaceName: string, outputFilePath: string) { // 模板生成逻辑 console.log(`生成接口${interfaceName}的模板:`, properties); } const project = new Project(); // 添加目标接口文件 const sourceFile = project.addSourceFileAtPath('./interfaces.ts'); // 获取所有接口并遍历 sourceFile.getInterfaces().forEach((iface) => { const interfaceName = iface.getName(); const properties = iface.getProperties().map(prop => ({ name: prop.getName(), type: prop.getType().getText() })); func(properties, interfaceName, './output.txt'); });
同样用ts-node运行脚本即可。
内容的提问来源于stack exchange,提问作者Sergino
相关产品推荐
相关产品推荐

