Reputation: 53
I've created a couple of Typescript classes, but when i instance them i get undefined error when i try to use them
I've tried to instance my field into constructor, it works but i don't believe this is a good practice.
export class Organization { name: string; code: string;}
export class Partner {
name: string;
organization: Organization;
}
const p = new Partner();
p.Organization.name = "ORG"; <----'Can't set "name" of undefined'
export class Partner {
name: string;
organization: Organization;
constructor(){
this.organization = new Organization(); <--- is there other way?
}
}
const p = new Partner()
p.Organization.name = "ORG" <--- it works already
Upvotes: 3
Views: 435
Reputation: 97331
There's no need to initialize the member in the constructor.
You can just do it as part of the property declaration:
export class Partner {
name: string;
organization: Organization = new Organization();
}
Upvotes: 2