0

以下代码示例按预期工作并打印出“[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"));

如果我在 Angular 2 项目中放置相同的代码,则会返回“function Object() { [native code] }”。

我为此准备了一个 Plunker: https ://plnkr.co/edit/DhXT89U0q5fCOWlCrx6w?p=preview

Reflect.getMetadata('design:type' ...) 仍然适用于自定义类和其他内置类。我只能用 Date 产生这个问题。

我究竟做错了什么?

4

1 回答 1

3

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

于 2017-01-18T09:45:18.230 回答