Home > database >  Undefined error when setting interface property typescript
Undefined error when setting interface property typescript

Time:12-08

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 = [];
  }

CodePudding user response:

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

CodePudding user response:

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;
  } = {};
  • Related