Class decorators

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

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

Consider a Customer class, and we would like that class to be freezed. Its existing properties should not be removed and 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 is the code snippet of the function written for the freezed decorator:

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

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.178