1

我有这堂课:

import { AccountRow } from './account-row';
export class Account {
  id?:number;
  name:string;
  rows: AccountRow[];
  public getTotal?(): number {
    let total: number = 0;
    if (!this.rows || this.rows.length == 0) {
      return total;
    }
    for(let r of this.rows) {
      total += r.amount;
    }
    return total;

  }
}

我尝试用以下内容填充它:

export class HomePage {
  accountForm: FormGroup;
  addRowForm: FormGroup;
  activeAccount: Account;

  constructor(public navCtrl: NavController) {
    // fixture for testing
    this.activeAccount = {
      name: "January balance",
      rows: [
        { description: "Car insurance", amount: 45.5, date: new Date() },
        { description: "Car insurance", amount: -20.5, date: new Date() }
      ]
    };
    console.log(this.activeAccount.getTotal());

  }
}

值已正确分配,但似乎对象分配正在破坏 getTotal 方法,当我执行它抛出的代码时:

Error: Uncaught (in promise): TypeError: this.activeAccount.getTotal is not a function
TypeError: this.activeAccount.getTotal is not a function

我想知道是否可以在不破坏实例方法且不实现初始化构造函数或工厂方法的情况下做到这一点

4

1 回答 1

0

在语言中没有办法做到这一点。使用类变压器 https://github.com/pleerock/class-transformer

于 2017-05-22T10:47:14.363 回答