Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to: Typescript instance fields to avoid undefined

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
like image 721
Moon Wolf Avatar asked Aug 01 '26 17:08

Moon Wolf


1 Answers

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();
}
like image 116
Robby Cornelissen Avatar answered Aug 04 '26 15:08

Robby Cornelissen