Notes

Javascript/Typescript Decorators Suck

January 3, 2025

I just spent a few days looking into implementing Javascript/Typescript decorators into a library and have come to the conclusion that the languages’ implementations are too poorly supported to be distributed in shared libraries.

There seems to be multiple incompatible decorator implementations including:

  1. An ES2016 decorator of the type function decorator(target, key, descriptor)
  2. A Typescript 4 decorator of the type function decorator(target, key, descriptor) which seems to be mostly the same as in ES2016 but still requires a "experimentalDecorators": true to be set in tsconfig.json
  3. And a Typescript 5 decorator of the type function decorator(originalMethod: Function, context: DecoratorContext): Function

All three decorator patterns work by declaring @decorator in front of the class, method, or property to be decoratored. All three decorator patterns do not work on bare functions. The first two have also been deemed “experimental” for years (ES2016 has been around for a decade) and are backwards incompatible with the currently supported decorator pattern in Typescript (not backported to ECMAScript) and therefore are also poorly supported by compilers like Babel and various munging tools like webpack.

It’s therefore pretty much impossible for a shared library to use decorators without resorting to shipping multiple decorator implementations (e.g. a @decorateES2016 as well as @decorateTypescript5) or having janky instructions like adding flags to node packages’ tsconfig.json.

I guess Javascript is still catching up to Python which has had decorators for 20+ years now.