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.
As well as decorating a whole class, we can decorate methods inside one. A method decorator can be used just before the declaration of a method in a class. They're applied to the property descriptor of the method, and like a class you can use it to observe, modify, or replace a method definition.
Method decorator expressions are called with three arguments. The first is the prototype of the class for an instance method or the constructor for a static method. The second is the name of the method. And the third is the property descriptor for the method. The property descriptor will be set by any value returned by the decorator.
The code we have ensures that a method of a class cannot be accidentally overwritten by making it read only. This is done by setting the enumerable and writable property descriptors to false. These are true by default. Read-only decorator takes a target, a method name, and a descriptor as arguments.
It then sets the writable and enumerable properties of the method to false, meaning it can't be changed by other code. In the class we decorate the sayHello method with the read-only decorator. When we have an instance of the class, we can call the method. But if we try and change the method by reassigning it, we'll get a runtime error.
The error highlighted on line 13 is because false is not a function, not because we shouldn't be reassigning sayHello. You can see that the compilation error shows this in the console too. We run the file.
As you can see the sayHello method was not changed after the declarations. It still logs out Hello twice. Is it got you here? TypeScript won't pick up on the enumerable era. It happens at runtime.
Each time it is applied to a method, would change whether it's read only or not. The method can have more than one decorator, which will execute when the method is called. Again, this is a fairly simple example we've got here and you can do more with method decorators. Again, we'll direct you towards the documentation and online searches to find out more.