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

向InventoryTransactionFullModel类型数组添加元素报错,求正确实现方式

自定义模型数组填充问题及解决方法

问题场景

我在尝试填充自定义模型类型的数组并将其传递给Service Component时遇到了问题。

声明的数组:

itemsCopied: Array<InventoryTransactionFullModel> = [];

提交方法中填充数组的代码:

this.itemsCopied.push({
  productWarehouseId: this.form.warehouseId.value,
  productStorageTypeId: this.form.storageTypeId.value,
  documentNumber: this.form.documentNumber.value,
  transactionDate: this.form.expenseDate.value,
  pSLId: this.form.productServiceLineId.value,
  description: this.form.description.value,
  totalAmount: this.form.totalAmount.value, 
  exchangeRate: this.form.defaultExchangeRate.value,
})

错误提示:类型“{ productWarehouseId: any; ... }”的参数不能赋给类型“InventoryTransactionFullModel”的参数。

正确填充方式

根据InventoryTransactionFullModel的定义类型,分两种情况处理:

情况1:InventoryTransactionFullModel是接口

检查以下几点:

  • 字面量的属性名是否和接口完全一致(注意大小写,比如pSLId是否和接口中的命名匹配)
  • 是否遗漏了接口中的必填属性
  • 属性值的类型是否和接口定义一致(比如transactionDate如果接口是Date类型,表单返回的可能是字符串,需要转换)

确认无误后,直接使用字面量即可,若仍有类型报错,可检查是否有隐式类型不匹配的情况。

情况2:InventoryTransactionFullModel是类

类的实例不能直接用字面量对象代替,必须先实例化类再赋值:

// 实例化类对象
const newTransaction = new InventoryTransactionFullModel();
// 逐个赋值属性
newTransaction.productWarehouseId = this.form.warehouseId.value;
newTransaction.productStorageTypeId = this.form.storageTypeId.value;
newTransaction.documentNumber = this.form.documentNumber.value;
newTransaction.transactionDate = this.form.expenseDate.value;
newTransaction.pSLId = this.form.productServiceLineId.value;
newTransaction.description = this.form.description.value;
newTransaction.totalAmount = this.form.totalAmount.value;
newTransaction.exchangeRate = this.form.defaultExchangeRate.value;
// 推入数组
this.itemsCopied.push(newTransaction);

如果类有接收属性的构造函数,也可以直接在实例化时传入参数:

this.itemsCopied.push(new InventoryTransactionFullModel(
  this.form.warehouseId.value,
  this.form.storageTypeId.value,
  this.form.documentNumber.value,
  this.form.expenseDate.value,
  this.form.productServiceLineId.value,
  this.form.description.value,
  this.form.totalAmount.value,
  this.form.defaultExchangeRate.value
));

临时解决方案(不推荐)

如果只是临时绕过类型检查,可以使用类型断言,但会失去TypeScript的类型校验能力:

this.itemsCopied.push({
  productWarehouseId: this.form.warehouseId.value,
  productStorageTypeId: this.form.storageTypeId.value,
  documentNumber: this.form.documentNumber.value,
  transactionDate: this.form.expenseDate.value,
  pSLId: this.form.productServiceLineId.value,
  description: this.form.description.value,
  totalAmount: this.form.totalAmount.value, 
  exchangeRate: this.form.defaultExchangeRate.value,
} as InventoryTransactionFullModel);

内容的提问来源于stack exchange,提问作者Hans

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:52:33