简体   繁体   中英

Undefined error when setting interface property typescript

I am receiving this error when I set involved to an empty array. Nothing I've tried has worked to resolve this issue.

Uncaught (in promise): TypeError: Cannot set properties of undefined (setting 'inPackage') TypeError: Cannot set properties of undefined (setting 'inPackage')

Model

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




 businessPayload: BusinessPayload = null;




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

You're setting this.businessPayload to null. When you set it to null, it will no longer be an object and therefore will not have keys. In your init function, you are trying to access business on this.businessPayload which is null. This throws an error, because there is nothing to find.

A solution could be to write something like this in your init function:

// 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";
  }
}

it's because business property is optional so typescript is considering it might be undefiend

I think it would be better to change in it to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM