Decorators

Decorators are also a TypeScript thing. Decorators in TypeScript decorate functions and classes, just as they do in some other languages, such as Python and Java.

We won't spend too much time here because we won't be writing our own decorators for the application we're going to build together, but since Angular makes use of decorators quite a bit, I wanted to at least give you an idea of what they are used for. We'll also look at a quick example of how to create one and how to use it, but we'll fly through it quickly.

Decorators are a way to add functionality to a function or a class (typically a class), by annotating the class with the decorator. The decorator is just a function, although it has some strange looking syntax at first glance. Let's look at some code:

function iq(target) {
Object.defineProperty(target.prototype, 'iq', {value: () => "Genius"})
}
@iq
class Person {
}
let readerOfMyBook = new Person();
console.log(readerOfMyBook.iq()); // prints out "Genius" to the console

This is intermediate to advanced level TypeScript, and an entire chapter can be written on decorators. We don't have the luxury to cover them in detail here, but the takeaway is that they are simply functions that add functionality to functions or classes, and to do that you only need to annotate the function or class with the name of the decorator (that is, @NameOfDecorator).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.152.250