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.
Property decorators can be used to observe if a specific name has been declared, and then perhaps do something with the value. A property decorator takes two arguments, the target, which is the current objects prototype and the property name, which is the name of the property.
Effectively we provide getter and setter methods for the property in the decorator, which could also use the Reflect API. But this needs the additional reflect-metadata library for use. The example shown uses getter and setter methods. The function looks like a single property class.
We set the value to whatever is passed in from the property. Get just returns the value. Set sets a new value based on the old value and a string we want to prepend it with. We then redefine the object property, setting the new value but the set function and returning the value with get.
The enumerable and configurable properties are set to true, so mutating is allowed. The class defines a decorated public username property as a string and the constructor sets it to an empty string by default. We then create an instance of the class on line 35.
Compiling and running at this point shows that the decorator runs with the empty string, and prepends the string in set to it with a mutate username directly and we see that the decorator runs again, replacing the empty string with the string we supplied.
If we try and access the username directly, we can see that the decorators get function is run before logging out the actual value. These property decorators run every time the property they are attached to is accessed.