How to Reset clear the values in a Typescript class

送分小仙女□ 提交于 2020-06-27 16:25:46

问题


How do I reset the values in a class in Typescript and ensure all the values are cleared? Is there a typescript function to do this?

export class Product{
   productId: number; 
   productName: string;
   productDescription: string;
}

We have many classes with 50+ fields, looking for efficient way to conduct this.


回答1:


Try like this:

Working Demo

productDetails: Product = {
  productId: 1,
  productName: "Apple",
  productDescription: "Fruit"
};

reset() {
  this.productDetails = new Product();
}



回答2:


YOu can create a function and set your all states to default value

export class Product{
  productId: number; 
  productName: string;
  productDescription: string;

  resetValues() {
    this.productId = 0; //default of number datatype is 0
    this.productName = null;
    this.productDescription = null;
  }
}


来源:https://stackoverflow.com/questions/58947764/how-to-reset-clear-the-values-in-a-typescript-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!