Decorators

Decorators are a stage 2 proposal feature for JavaScript and are available as an experimental feature of TypeScript. Decorators, at their core, are just functions. Such functions can be used on different kinds of declarations, such as classes and their members, as well as parameters.

Decorators can emit metadata that can be inspected later by other code or processes, enabling a meta-programming style. Considering your background in .NET, you can think about TypeScript decorators as .NET attributes. Unlike .NET attributes, though, decorator functions can actually manipulate the decorated code.

Decorators are considered a somewhat advanced feature of TypeScript and there's much to learn in that regard. The depth of this feature is not in the scope of this chapter yet, so it is important that you get you familiar with it since Angular uses it quite extensively.

The following is an example of a simple class decorator that logs to the console every time a decorated class is instantiated:

function logClassInit(target: any) {
// preserve a reference to the original constructor
const original = target;

// a class instance factory
function construct(constructor, args) {
const c: any = () => constructor.apply(this, args);
c.prototype = constructor.prototype;
return new c();
}

// the new constructor behavior
const f: any = (...args) => {
console.log("Instantiated: " + original.name);
return construct(original, args);
};

// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
}

@logClassInit
class Person {}

const p = new Person(); // logs to the console: `Instantiated: Person`

In the preceding example, the decorator logClassInit is implemented and, as you can see, it's just a function. The implementation is basically replacing the constructor with a utility one that logs to the console and then uses the original constructor.

Decorators are applied using the at sign, @. In the preceding code, you can see that the decorator is applied to the Person class by annotating it with the decorator function (@logClassInit). Now, whenever the code instantiates Person, a log is written to the console.


Decorators are an experimental feature in TypeScript.
To support them, you must specify the experimentalDecorators flag when using tsc
: 

tsc --experimentalDecorators
..................Content has been hidden....................

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