What Are Decorators?
Explore the concept of decorators in TypeScript, understanding how they allow injecting code into class definitions before instantiation. Learn about their syntax, enabling decorators in the compiler, usage with multiple decorators, and their application in frameworks like Angular and Vue.
We'll cover the following...
Introduction
Decorators in TypeScript provide a way of programmatically tapping into the process of defining a class. Remember that a class definition describes the shape of a class, what properties it has, and what methods it defines. When an instance of a class is created, these properties and methods become available on the class instance. Decorators, however, allow us to inject code into the actual definition of a class before a class instance has been created. They are similar to attributes in C# or annotations in Java.
JavaScript decorators are currently only at a draft or stage two level, meaning that it may take a while before they are adopted into the JavaScript standard. TypeScript, however, has supported decorators for quite some time, although they are marked as experimental. Decorators have also become popular due to their use within frameworks such as Angular, where they are primarily used for dependency injection, or Vue, where they are used to inject functions into a class definition.
Note: It must be said that this topic comes with a warning ...