官术网_书友最值得收藏!

Class decorators

Class decorators are declared above the class declaration. Class decorators can observe, modify, and replace a class' definition that it is decorated by applying to the constructor of that class. The signature of ClassDecorator in TypeScript is as follows:

declare type ClassDecorator = <TFunction extends Function>(target:  
      TFunction) => TFunction | void; 

Consider a Customer class; we would like that class to be frozen. Its existing properties should not be removed or new properties should not be added.

We can create a separate class that can take any object and freeze it. We can then decorate the customer class with @freezed to prevent adding new properties or removing the existing properties from the class:

@freezed 
class Customer { 
  
  public firstName: string; 
  public lastName: string; 
  
  constructor(firstName : string, lastName : string) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
  } 
} 

The preceding class takes four arguments in the firstname and lastname constructors. The following are the code snippets of the function written for the @freezed decorator:

function freezed(target: any) { 
    Object.freeze(target); 
} 

Here, the freezed decorator takes target, which is the Customer class that is being decorated, and freezes it when it gets executed.

主站蜘蛛池模板: 鸡泽县| 辰溪县| 平潭县| 海门市| 登封市| 双峰县| 阜阳市| 乾安县| 兴安盟| 综艺| 象州县| 突泉县| 延长县| 枝江市| 乌拉特前旗| 青阳县| 依安县| 峨眉山市| 神农架林区| 东方市| 大连市| 永安市| 从化市| 榆中县| 伊金霍洛旗| 玉屏| 昌吉市| 项城市| 宜川县| 承德市| 南昌县| 韶山市| 宜宾市| 勐海县| 吉隆县| 鹿泉市| 慈溪市| 建宁县| 汽车| 禹城市| 华安县|