Reflect.decoration与在TypeScript中手动修饰
我有两个装饰师,如下所示:Reflect.decoration与在TypeScript中手动修饰,typescript,metaprogramming,Typescript,Metaprogramming,我有两个装饰师,如下所示: import "reflect-metadata"; const enum MetadataTypes { Type = "design:type", Paramtypes = "design:paramtypes", ReturnType = "design:returntype" } function Decorator1(target: any, key: string): void { console.log(`Applied Decora
import "reflect-metadata";
const enum MetadataTypes {
Type = "design:type",
Paramtypes = "design:paramtypes",
ReturnType = "design:returntype"
}
function Decorator1(target: any, key: string): void {
console.log(`Applied Decorator1 to ${key} on ${target.constructor.name}`);
const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
console.log(type.name);
}
function Decorator2(target: any, key: string): void {
console.log(`Applied Decorator2 to ${key} on ${target.name}`);
const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
console.log(type);
}
一种是手动应用的:
export class MyClass {
@Decorator1
private foo: string;
}
另一个使用Reflect.decoration
:
Reflect.decorate([Decorator2], MyClass, "foo");
为什么使用Reflect应用的decorator无法检索数据类型
注销输出为:
Applied Decorator1 to foo on MyClass
String
Applied Decorator2 to foo on MyClass
undefined
要使用
Reflect.decort
,您必须通过类的原型来实现类似的行为
import "reflect-metadata";
const enum MetadataTypes {
Type = "design:type",
Paramtypes = "design:paramtypes",
ReturnType = "design:returntype"
}
function Decorator1(target: any, key: string): void {
console.log(`Applied Decorator1 to ${key} on ${target.constructor.name}`);
const type = Reflect.getMetadata(MetadataTypes.Type, target, key);
console.log(type.name);
}
export class MyClass {
private foo: string;
}
Reflect.decorate([Decorator1], MyClass.prototype, "foo");
// Output:
// Applied Decorator1 to foo on MyClass
// undefined
问题在于,在使用Reflect.decoration
时,不会生成元数据
使用decorator语法使编译器保存元数据(当启用了配置选项时,emitdecorormatadata
可以通过Reflect.getMetadata
访问)
您可以在此处阅读: