示例说明
类型信息在编译后即被擦除,运行时拿不到字段清单。ts-morph 提供 AST 级的读写能力:读取真实源文件、遍历接口属性、生成新文件,把类型侧的知识以常量形式带回运行时。典型用途是字段白名单、表单动态渲染与前后端契约同步——单一源码定义,双端自动派生。
技术要点
- createSourceFile 同时支持读取与生成
- 接口属性遍历得到字段名数组
- 生成文件显式 save 落盘
代码解读
项目实例先创建契约源与输出源两个内存文件;循环里检查导出关键字过滤公开接口,把属性名序列化为 as const 元组语句追加进生成文件。最后 save 写盘并断言两个接口的字段常量都已生成。
使用建议
生成代码要标注自动生成头注释并加入 git 检查防止手改。生成步骤挂在 prebuild 钩子,保证产物与源同步。AST 遍历错误要有构建期失败兜底。
代码示例
import { Project, InterfaceDeclaration } from 'ts-morph';
const project = new Project({
compilerOptions: { strict: true, declaration: false },
skipAddingFilesFromTsConfig: true,
});
const source = project.createSourceFile(
'src/contracts.ts',
`
export interface Order {
id: string;
total: number;
status: 'pending' | 'paid' | 'refunded';
}
export interface Customer { name: string; vip: boolean }
`,
);
const generated = project.createSourceFile('src/generated/fields.ts', '', {
overwrite: true,
});
for (const iface of source.getInterfaces()) {
if (iface.getExportKeyword() === undefined) continue;
const fields = iface
.getProperties()
.map((prop) => prop.getName())
.map((name) => ` ${JSON.stringify(name)},`)
.join('\n');
generated.addStatements(
`export const ${iface.getName()}Fields = [\n${fields}\n] as const;`,
);
}
generated.addStatements('export type FieldMap<T> = { [K in keyof T]: K };');
await generated.save();
console.log(generated.getFullText().includes('OrderFields'));
console.log(generated.getFullText().includes('CustomerFields'));