TypeScript类型生成工具无法正确处理可空字段问题求助
解决ts-morph生成类型时丢失
null类型信息的问题 问题分析
你当前的代码提取Row类型并生成新类型时,| null被自动省略,核心原因有两点:
rowType.getText()默认的类型格式化选项会忽略null/undefined这类可空标记;- 若未开启
strictNullChecks,TypeScript类型检查器会自动合并可空类型,导致输出文本丢失| null。
解决方案
1. 配置类型格式化选项,强制保留可空类型
调用getText()时,显式传入TypeFormatFlags参数,指定包含可空类型:
首先导入TypeFormatFlags:
import { TypeFormatFlags } from "ts-morph";
修改generateTypes函数中的rowTypeString获取逻辑:
const rowTypeString = rowType.getText({ typeFormatFlags: TypeFormatFlags.IncludeUndefinedOrNull | TypeFormatFlags.NoTruncation });
2. 开启严格空检查
在Project的编译器配置中添加strictNullChecks: true,让TypeScript正确识别并保留可空类型:
const project = new Project({ compilerOptions: { allowSyntheticDefaultImports: true, esModuleInterop: true, module: ModuleKind.ESNext, target: ScriptTarget.ESNext, strictNullChecks: true, // 新增配置 }, });
3. 备选方案:直接读取声明节点的源代码文本
如果上述方法仍有问题,可以跳过类型检查器的处理,直接获取Row类型的原始声明文本:
export function generateTypes(table: Symbol, tableName: string): string[] { const tableType = table.getTypeAtLocation(table.getValueDeclarationOrThrow()); const rowProperty = tableType.getProperty('Row'); // 直接获取Row的声明节点文本并移除前缀 const rowDeclaration = rowProperty.getValueDeclarationOrThrow(); const rowTypeString = rowDeclaration.getText().replace(/^\s*Row:\s*/, ''); const types: string[] = []; types.push( `export type ${toTypeName(tableName)} = ${rowTypeString};` ); return types; }
修改后效果
重新运行代码,生成的Profile类型会正确保留| null:
export type Profile = { first_name: string | null; id: string; last_name: string | null; };
内容的提问来源于stack exchange,提问作者Barry Michael Doyle
相关产品推荐
相关产品推荐

