如何无需逐个输入属性创建Prisma空模型对象?
如何快速创建Prisma模型的空对象实例
不需要完全手动为每个模型创建空对象,有几种简便方法可以复用逻辑:
1. 基于Prisma生成的类型初始化
Prisma会自动根据你的模型生成对应的TypeScript类型(比如Compra),你可以基于这个类型快速初始化空对象,保证类型匹配:
import { Compra } from '@prisma/client'; const emptyCompra: Compra = { id: 0, createdAt: new Date(), // Prisma的DateTime对应JS的Date类型,若要空字符串需做类型转换(不推荐) anoMes: '', fecha: new Date(), ccf: '', neto: 0, iva: 0, excento: 0, total: 0, proveedorId: 0, // 注意:关联字段proveedor默认不在基础Compra类型中,若需要嵌套结构,需手动补充或扩展类型 };
2. 编写通用初始化函数
如果有多个模型需要生成空对象,可以写一个通用函数,根据字段类型自动填充默认空值:
import { Decimal } from '@prisma/client/runtime/library'; function createEmpty<T>(modelType: T): T { const empty: any = {}; for (const key in modelType) { const sampleValue = modelType[key]; if (typeof sampleValue === 'number') { empty[key] = 0; } else if (typeof sampleValue === 'string') { empty[key] = ''; } else if (sampleValue instanceof Date) { empty[key] = new Date(); // 或根据需求设为空字符串 } else if (sampleValue instanceof Decimal) { empty[key] = new Decimal(0); } else if (typeof sampleValue === 'object') { empty[key] = createEmpty(sampleValue); } else { empty[key] = ''; } } return empty as T; } // 使用示例 import { Compra } from '@prisma/client'; const emptyCompra = createEmpty<Compra>({} as Compra);
这个函数可以根据不同字段类型(数字、字符串、Date、Decimal、嵌套对象)自动生成对应空值,适配大部分Prisma模型。
3. 复用手动模板(适合少量模型)
如果模型数量不多,也可以把空对象做成常量模板,使用时直接复制或解构:
export const EMPTY_COMPRA = { id: 0, createdAt: '', anoMes: '', fecha: '', ccf: '', neto: 0, iva: 0, excento: 0, total: 0, proveedor: { id: 0, nombre: '', registo: '' }, proveedorId: 0, }; // 使用时创建副本 const empty = { ...EMPTY_COMPRA };
内容的提问来源于stack exchange,提问作者Ben Quan
相关产品推荐
相关产品推荐

