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

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.

主站蜘蛛池模板: 蚌埠市| 大新县| 乌鲁木齐县| 连山| 商都县| 闸北区| 偃师市| 金坛市| 虹口区| 清水河县| 慈溪市| 大余县| 江西省| 望都县| 宁南县| 西峡县| 平和县| 南雄市| 潢川县| 抚顺县| 双江| 雷波县| 明溪县| 乌兰察布市| 阿克苏市| 陇南市| 竹溪县| 达日县| 密山市| 永春县| 溆浦县| 锡林浩特市| 丹江口市| 丽江市| 乌拉特前旗| 桃江县| 同心县| 玛多县| 英吉沙县| 阜阳市| 昌乐县|