如何:Typescript 实例字段以避免未定义

How to: Typescript instance fields to avoid undefined

我已经创建了几个 Typescript 类,但是当我实例化它们时,当我尝试使用它们时出现未定义的错误

我已经尝试将我的字段实例化到构造函数中,它有效,但我认为这不是一个好的做法。

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

不需要在构造函数中初始化成员。

您可以将其作为 属性 声明的一部分:

export class Partner {
  name: string;
  organization: Organization = new Organization();
}