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 email@example.com to let us know what you think.
As you've already seen, a class decorator is declared just before a classes declaration. The simple one you may have seen a minute ago didn't really do anything to the class. A class decorator works with the constructor of the class and we can use it to observe, modify or replace a class definition.
The constructor is the only argument a class decorator can take. Whatever we define as the expression for the class decorator will execute as a function at runtime. In this example, we write a decorator to merge additional properties into a class. This could be useful if you have a base class that needs additional properties.
You could extend this class or write an interface to achieve this. But decorators provide another alternative and this could be used across a number of separate base classes to add the same fields or different fields depending on the object pass to the decorator. When you create a decorator for a class, the object passed into the function is the constructor.
You should recognize that merge is a decorator factory. It expects to receive an object to work with, namely, the item we're decorating with. It returns a function. And it's this that receives the constructor of the class for decorating. We loop through the properties in the object supplied and set a property on the targets prototype based on the object passed in.
Under the class declaration, we create an instance called my user. And then through casting my user to any to avoid typing issues with the person class, we access the properties passed in by the decorator. When we compile this and run it, you can see that we can access the properties added by the decorator.
There are other things we could do here, like overriding the constructor itself, or changing its properties and the values. You can find out how to do these things from the documentation. And there's some examples if you search online.
Ed is an Outstanding Trainer in Software Development, with a passion for technology and its uses and holding more than 10 years’ experience.
Ed is responsible for delivering QA’s Programming Foundations course using the Eclipse IDE. His skillset extends into the DevOps sphere, where he is able to deliver courses based around Agile/Scrum practices, version control, and CI/CD.