Typescript Reflect.getMetadata('design:type

2019-09-14 21:55发布

问题:

The following code Sample is working as expected and prints out "[Function: Date]"

import 'reflect-metadata'
function logType(target : any, key : string) {
     var t = Reflect.getMetadata("design:type", target, key);
     console.log(`${key} type: ${t.name}`);
   }
export class Demo {
  @logType // apply property decorator
  test: Date;
}
let demo = new Demo();
console.log(Reflect.getMetadata('design:type', demo, "test"));

If I place the same code within an Angular 2 Project, "function Object() { [native code] }" is returned.

I prepared a Plunker for this: https://plnkr.co/edit/DhXT89U0q5fCOWlCrx6w?p=preview

Reflect.getMetadata('design:type' ...) is still working for custom classes and other builtin classes. I could only produce this problem with Date.

What am I doing wrong?

回答1:

You have to execute the function, and not just.. put it there :), you should add parentheses after @logType

export class Demo {
  @logType() // add parentheses 
  test: Date;
}

On the other hand you should change your @logType function to something like this:

function logType(type: any) {
  return function(target: any, propertyKey: string) {  
     Reflect.defineMetadata('design:type', type, target, propertyKey);
  }
}

Which you can call like this:

export class Demo {
  @logType(Date) // apply property decorator
  test: Date;
}

I've updated the plnkr to show what I mean: plnkr

You can only get either string, boolean, number or object with the built-in types. Where object will be anything, from Date to Array to your Math and WeakMap. All built-ins will evaluate to Object, I'm not sure if this a bug, or by design.

You can however use your method to get custom classes. If you would do

export class Demo {
  @logType
  test: Demo;
}

It will print out Demo