Dmitry Parzhitsky Dmitry Parzhitsky - 3 years ago 192
TypeScript Question

What is `Reflect.decorate` in JS code transpiled from TS?

While playing with decorators on TypeScript playground I've noticed, that on the line #3 transpiled code checks the existence the


What is this function about? I didn't manage to find this neither on SO, nor on MDN documentation about

Answer Source

The answer to your question lies right in the next line in the transpiled code:

else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;

To understand it you need to keep in mind these things:

  • A decorator is just a function that will allow you to observe, modify, or replace the behavior of a class or a class member
  • There are 4 types of decorators: class decorators, method decorators, accessor decorators, and property decorators
  • Each type of decorator gets passed a particular set of arguments:
    • Class decorators take the class constructor
    • Method and accessor decorators take either the class constructor or class prototype (depends on whether they're static or instance members), the name, and the property descriptor
    • Property decorators take the same arguments of method and accessor decorators excepting the last one

Now, if you read again, you see that "Reflect.decorate" is a method that goes through the list of decorators that you intend to apply, then identifies the type of decorator based on the number of arguments, and finally calls the decorator with the right arguments (based on the type that it detected).

Why do they check for the existence of Reflect.decorate if they have it right there?

Because at some point in the future they expect Reflect.decorate to become part of the ES standard and then be implemented in browsers accordingly. At that moment, they'd rather use the native method than this polyfill.

As this method is part of "ES.later" (not even, no browser has implemented it natively yet, and for that reason nobody documents it yet.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download