Decorators are functions that modify a class, property, method, or method parameter. The following example illustrates how to define and use a simple decorator that adds a static parameter to the class:
// decorator function function AddMetadata (...args) { return function (target){ target.metadata = [...args]; } } // decorator applied @AddMetadata({ metadata: 'some values'}) class Model { }
The three dots syntax (...
) is the spread operator, which is a feature of JavaScript 2015 that deconstructs the items of a given array.
You might have heard the term annotations; they are simply metadata related to Angular 2. Before the Angular team decided to use TypeScript, they introduced us to a new language that they called AtScript. This language included a feature called annotations, which look exactly like decorators. So what's the difference? The decorator is an interface for creating those Angular annotations. Decorators are executed and in...