尝试设置值时接口属性未定义?

时间:2019-11-24 00:08:13

标签: angular typescript class interface

这是我的篮球运动员班以及ITeam和IStats界面:

export class Player {
  id: string;
  firstName: string;
  lastName: string;
  position: string;
  team: ITeam;
  stat: IStats;

  get fullName(): string {
    return this.firstName + " " + this.lastName;
  }
}

export interface ITeam {
  id: string;
  abbreviation: string;
  name: string;
  city: string;
}

export interface IStats {
  GP: number;
  Min: number;
  FGM: number;
  FGA: number;
  TPM: number;
  TPA: number;
  FTM: number;
  FTA: number;
  OR: number;
  TR: number;
  AS: number;
  ST: number;
  TO: number;
  BK: number;
  PF: number;
  DQ: number;
  PTS: number;
  TC: number;
  EJ: number;
  FF: number;
  Sta: number;
}

当我遍历组件中的数据时,尝试使用ERROR TypeError设置player.team.abbreviation属性时会出错:无法设置未定义的属性'abbreviation'

  createPlayer(playerArray) {
    let player: IPlayer = new Player();

    player.id = playerArray[0];
    player.firstName = playerArray[1];
    player.lastName = playerArray[2];
    player.team.abbreviation = playerArray[3];
...
    }

为什么没有定义player.team?

1 个答案:

答案 0 :(得分:0)

感谢R.Richards,此更新现在有效:

export class Player {
  id: string;
  firstName: string;
  lastName: string;
  position: string;
  team: ITeam;
  stat: IStats;

  constructor() {
    this.team = {} as ITeam;
    this.stat = {} as IStats;
  }

  get fullName(): string {
    return this.firstName + " " + this.lastName;
  }
}