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

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.

主站蜘蛛池模板: 四川省| 凤阳县| 孝义市| 太仆寺旗| 新源县| 丹东市| 都匀市| 乃东县| 汝南县| 长汀县| 塘沽区| 洱源县| 阜平县| 自贡市| 嵊州市| 五指山市| 北川| 芜湖市| 香格里拉县| 禹州市| 钦州市| 黔江区| 永平县| 台江县| 府谷县| 思茅市| 仪陇县| 弥勒县| 南靖县| 巩义市| 柘城县| 南昌县| 方正县| 阿拉善左旗| 阿尔山市| 图木舒克市| 乌苏市| 高唐县| 淮北市| 凌源市| 台江县|