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

TypeScript类型生成工具无法正确处理可空字段问题求助

解决ts-morph生成类型时丢失null类型信息的问题

问题分析

你当前的代码提取Row类型并生成新类型时,| null被自动省略,核心原因有两点:

  1. rowType.getText()默认的类型格式化选项会忽略null/undefined这类可空标记;
  2. 若未开启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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:23:33