The course is part of this learning path
This module looks at what decorators are and how you can use them in your TypeScript applications.
The objectives of this module are to provide you with an understanding of:
- What simple decorators and decorator factories are
- How to create Class Decorators
- How to create Method Decorators
- How to create Property Decorators
- How to create Accessor Decorators
This learning path is aimed at all who wish to learn how to use TypeScript
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
The accessor decorators are used to decorate getting set methods in a class. They work on the property descriptor and can be used to observe, modify or replace an accessor definition. This can be particularly useful in hiding properties from iterators, by setting the enumerable value.
We create a decorator factory to allow the setting of a property to true or false. The expression returned is pretty much the same as the method decorator, taking a target property name and a property descriptor as arguments. We then set the enumerable property of the descriptor.
The class has two private fields and getting set for them. You'll notice that the get functions are decorated. User name is true, password is false. We then create an instance of the class on line 27, setting the username. We also access password and set its value on line 29 and then log out. On line 32 we Create a loop, through each of new users innumerable properties, locking the name of the property and its value out.
Compiling and running there shows, that the enumerable property of each has been defined, for its set function. You can see that the password is not included in the foreign iterator running, or because enumerable was set to false. So that's the different types of decorators available in TypeScript, and an overview of how they work.
It's quite probable that you'll never write your own decorator, but they are used extensively in Angular, and some of the frameworks and libraries. So it's good to know about how they work. There's more information and examples online. Don't forget, unless it becomes a concrete part of the specification, the implementation may change. But for now, go and get some practice with them.