typescriptreflect-metadata

Why is reflect-metadata only working when using a decorator?


Without decorators the metadata is lost - but why?

const Baz = () : ClassDecorator => {
  return target => {}
}
class Bar {}
@Baz()
class Foo {
  constructor(bar: Bar) {}
}
console.log(Reflect.getMetadata('design:paramtypes', Foo));

This returns [Function: Bar], which is fine. But without the @Baz decorator (which does literally nothing) it returns undefined. Why?


Solution

  • The PR that implements this feature states:

    emit design-time type metadata for decorated declarations in source.

    So it explicitly was designed to emit metadata just if there is a decorator on a class.

    I am unable to find the rationale behind this decision, but my guess it that it would be wasteful to emit this code for all classes (js is sensitive to size) and decorators and metadata are seen as related concepts.