Decorators: The Next Generation

Learn how to implement a decorator for class and method modifications.

Decorators let us craft a function that tweaks the behavior of a class and its methods. Imagine needing to sneak in some debug statements into our methods. Before TypeScript 5.0, we’d have copied and pasted the debug statements manually in each method. With decorators, we do the job once, and the change will be supported through each method the decorator attaches to.

Decorators have almost been part of ECMAScript. These nifty tools let us modify classes and members in a reusable way. They’ve been on the scene for a while in TypeScript—albeit under an experimental flag. Although the stage 2 iteration of decorators was always experimental, decorators have been widely used in libraries like MobXhttps://mobx.js.org/enabling-decorators.html, Angularhttps://angular.io/, Nesthttps://docs.nestjs.com/custom-decorators, and TypeORMhttps://typeorm.io/. TypeScript 5.0’s decorators are fully in sync with the ECMAScript proposalhttps://github.com/Educative-Content/proposal-decorators, which is ready for prime time at stage 3.

How to implement the @deprecated decorator

Let’s say we want to create a decorator for logging that a given method is deprecated:

Get hands-on with 1400+ tech skills courses.