如果使用Angular 2堆栈,则Typescript Reflect.getMetadata('design:type'..)返回Object而不是Date. [英] Typescript Reflect.getMetadata('design:type'..) returns Object instead of Date if the Angular 2 Stack is used
问题描述
以下代码示例按预期运行,并打印出"[功能:日期]"
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"));
如果我在Angular 2项目中放置相同的代码,则会返回"function Object(){[native code]}".
If I place the same code within an Angular 2 Project, "function Object() { [native code] }" is returned.
我为此准备了一个柱塞: https://plnkr.co/edit/DhXT89U0q5fCOWlCrx6w?p=preview
I prepared a Plunker for this: https://plnkr.co/edit/DhXT89U0q5fCOWlCrx6w?p=preview
Reflect.getMetadata('design:type'...)仍适用于自定义类和其他内置类.我只能用Date产生这个问题.
Reflect.getMetadata('design:type' ...) is still working for custom classes and other builtin classes. I could only produce this problem with Date.
我在做什么错了?
推荐答案
您必须执行函数,而不仅仅是将其放置在.)中,您应该在 @logType
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;
}
另一方面,您应该将您的 @logType
函数更改为以下内容:
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);
}
}
您可以这样拨打电话:
export class Demo {
@logType(Date) // apply property decorator
test: Date;
}
我更新了plnkr以显示我的意思: plnkr
I've updated the plnkr to show what I mean: plnkr
您只能获取具有内置类型的 string
, boolean
, number
或 object
. object
是什么,从 Date
到 Array
到您的 Math
和 WeakMap
.所有内置函数的求值结果都为 Object
,我不确定这是错误还是设计使然.
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;
}
它将打印出 Demo
这篇关于如果使用Angular 2堆栈,则Typescript Reflect.getMetadata('design:type'..)返回Object而不是Date.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!