Search code examples
typescriptreflectionreflect-metadata

Access class decorator argument using reflect-metadata


Consider a class decorator with one argument:

@TableName("Orders")
export class Order {
 // ...
}

And the decorator defined as:

import "reflect-metadata";

const classDecoratorKey = Symbol.for("custom:TableName");

export function TableName(tableName: string): ClassDecorator {
  return (constructor: Function) => {
    Reflect.defineMetadata(classDecoratorKey, tableName, constructor);
  }
}

export function getTableName(target: any): string {
  return Reflect.getMetadata(classDecoratorKey, target.constructor, "class") || "";
}

I expect now to get the @TableName value "Orders". How can I retrieve the class decorator's argument value?

let order = new Order();
getTableName(order); // "" but expected "Orders"

Solution

  • Here's what worked for me

    export function TableName(tableName: string): ClassDecorator {
      return (constructor: Function) => {
        Reflect.defineMetadata(classDecoratorKey, tableName, constructor.prototype);
      };
    }
    
    export function getTableName(target: any): string {
      return Reflect.getMetadata(classDecoratorKey, target) || '';
    }