【问题标题】:Cannot set property 'name' of undefined Typescript class无法设置未定义的 Typescript 类的属性“名称”
【发布时间】:2019-10-25 02:10:53
【问题描述】:

t.budget.budgetGroup.name 这里有上述错误。我无法重新创建此错误。但是 Sentry 将其显示为运行时异常。这可能吗?因为我已经初始化了new Budget()new BudgetGroup()。那么我该如何解决呢?

  data: DtoBudgetGroup;

  constructor(){}

  init() {
    this.data = this.navParams.get('data');
  }

let filteredTransactions: Transaction[] = filter(this.data.transactions, (t: 
Transaction) => { return t.budget.budgetGroup.name == this.data.budget.budgetGroup.name; });

export class Transaction {
    id: string;
    budget: Budget = new Budget();
  }

export class Budget {
    id: string;
    budgetGroup: BudgetGroup = new BudgetGroup();    
}

export class BudgetGroup {
    id: string;
    name: string;

}

export class DtoBudgetGroup {
    budget: Budget;
    budgetGroup: BudgetGroup;
    budgetTotal: number;
    transactionTotal: number;
    transactions: Transaction[];
    isTransactionOver: boolean = false;
}

this.data = this.navParams.get('data');

【问题讨论】:

  • 这取决于 this.data.transactions 是如何初始化的。如果它是 Web API 的响应,那么您的类将不会自行实例化。获得 JSON 数据后,您需要通过将 JSON 数据映射到所需的类集合来实例化。
  • @user2216584 我添加了更多数据。请看。没有 API。这是Firestore 数据。
  • 是的,你称之为@user2216584 - 一个异步问题 - 不是打字稿问题。
  • @RandyCasburn 你错了。这里的数据是预先的。这里没有异步问题。请清楚阅读问题。 this.data = this.navParams.get('data')
  • @Sampath 你能在 this.data = this.navParams.get('data'); 之后分享 console.log(this.data) 的输出吗?

标签: javascript angular typescript ionic3


【解决方案1】:

您的代码中的问题是,当您键入时

class MyClass {

prop: stirng;

}

您只是在声明一组属性及其类型。

但是,您不会初始化它们。要初始化,您需要一个构造函数。

你有两种方式来声明类的道具

export class BudgetGroup {
  constructor(
      public id?: string,
      public name?: string
    ) {
    }
}

export class BudgetGroup {
    id: string;
    name: string;

     constructor(
      id: string,
      name: string
    ) {
      this.id = id;
      this.name = name;
    }
}

你可以看到here的例子


没有 prop 初始化,因此调用 new BudgetGroup 会导致空对象。要初始化它们,您应该使用传递道具的构造函数或在类中声明这些道具值。

更新。专为兰迪卡斯本而设

【讨论】:

  • 即使这个答案并不完全不正确,它也不能回答 OP 关于BudgetGroup 属性的问题——它已经被初始化了。
  • @RandyCasburn 它确实回答了这个问题。 2)道具没有初始化,这可以在我的链接const a上看到。
  • 这个:要初始化你需要一个构造函数。 - 是错误的。你的链接也指出了这一点。
  • 这个name 属性的初始化应该发生在filter() 调用中,其中从init() 方法检索的数据中对t.budget.budgetGroup.name 进行赋值语句。 OP 正在初始化属性。只是在施工时。这是一个后期对象创建任务。并感谢您的来电!!
  • @RandyCasburn 您是否尝试过创建一个 OP 仅提供接口的对象? TypeScript 就是这样工作的。您可以在构造函数中初始化值,也可以在声明时初始化值,但它需要值。甚至null 也可以做到这一点。在这种情况下,界面是在没有道具的情况下创建的。
猜你喜欢
  • 2019-01-31
  • 2021-08-03
  • 2019-06-23
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
相关资源
最近更新 更多