设置接口属性typescript时出现未定义的错误

t3irkdon  于 2022-12-14  发布在  TypeScript
关注(0)|答案(2)|浏览(235)

当我将参与设置为空数组时,收到此错误。我尝试了所有方法来解决此问题。
未被捕获的(在承诺中):TypeError:无法设置未定义(设置“inPackage”)的属性TypeError:无法设置未定义的属性(设置“inPackage”)

型号

export class BusinessPayload implements Business {
  _id?: string;
  business?: {
    inPackage: string[];
    status: string;
  };
  description: string;
}



 businessPayload: BusinessPayload = null;



  ngOnInit() {
    this.businessPayload.business.inPackage = [];
  }
w6lpcovy

w6lpcovy1#

您正在将this.businessPayload设置为null。当您将其设置为null时,它将不再是一个对象,因此将没有键。在您的init函数中,您试图访问this.businessPayload上的business,该值为null。这将引发错误,因为没有要查找的内容。
一个解决方案是在init函数中编写如下代码:

// A check to make sure the payload is not null
if( !this.businessPayload ){
  this.businessPayload = {};
}

if( business in this.businessPayload && inPackage in this.businessPayload.business ){
  this.businessPayload.business.inPackage = [];
} else {
  this.businessPayload.business = {
    inPackage: [];
    status: "default";
  }
}
1szpjjfi

1szpjjfi2#

这是因为业务属性是可选的,所以typescript认为它可能是不确定的
我想不如就把它改成这样:

business: {
    inPackage?: string[];
    status?: string;
  } = {};

相关问题