What Are Decorators?
Learn about decorators in TypeScript and how to set up our TypeScript project to support decorators.
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 upfront. Since decorators are only at the draft level, and with TypeScript only supporting them as experimental, the implementation and standards for both JavaScript and TypeScript could change at any time. This means that we could craft some very fine decorator code, but changes to the specifications could introduce breaking changes, forcing a significant amount of rework. The purpose of this chapter is, therefore, to introduce and understand decorators, particularly for those who are using them heavily in frameworks.
Get hands-on with 1400+ tech skills courses.