- Expert Angular
- Mathieu Nayrolles Rajesh Gunasundaram Sridhar Rao
- 192字
- 2021-07-15 17:05:34
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.
- Embedded Linux Projects Using Yocto Project Cookbook
- JavaScript高效圖形編程
- GeoServer Cookbook
- Learn to Create WordPress Themes by Building 5 Projects
- Building a Game with Unity and Blender
- 數據結構習題精解(C語言實現+微課視頻)
- Instant QlikView 11 Application Development
- Python機器學習算法與實戰
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Hands-On Reinforcement Learning with Python
- 從Excel到Python:用Python輕松處理Excel數據(第2版)
- 計算機應用基礎案例教程
- 編寫高質量代碼:改善Objective-C程序的61個建議
- Machine Learning With Go
- Xcode 6 Essentials