当我在 TypeScript 中定义装饰器时,格式如下:
function Log2(target: any, name: string, descriptor: PropertyDescriptor) {
…
console.log(descriptor);
…
}
描述符显示为空。我使用 VS Code,
tsconfig.json
中的目标是
"target": "ES2016"
。我还启用了"experimentalDecorators": true
。
我的 VS Code 版本是 1.70.2,TypeScript 版本是 4.7.3。
我在这里做错了什么?为什么描述符总是为空?
app.ts 中的代码只是简单的函数,如下所示
function Log(target: any, propertyName: string | Symbol) {
console.log("Property decorator!");
console.log(target, propertyName);
}
function Log2(target: any, name: string, descriptor: PropertyDescriptor) {
console.log("Accessor decorator!");
console.log(target);
console.log(name);
console.log(descriptor);
}
function Log3(
target: any,
name: string | Symbol,
descriptor: PropertyDescriptor
) {
console.log("Method decorator!");
console.log(target);
console.log(name);
console.log(descriptor);
}
function Log4(target: any, name: string | Symbol, position: number) {
console.log("Parameter decorator!");
console.log(target);
console.log(name);
console.log(position);
}
class Product {
@Log
title: string;
private _price: number;
@Log2
set price(val: number) {
if (val > 0) {
this._price = val;
} else {
throw new Error("Invalid price - should be positive!");
}
}
constructor(t: string, p: number) {
this.title = t;
this._price = p;
}
@Log3
getPriceWithTax(@Log4 tax: number) {
return this._price * (1 + tax);
}
}
当我尝试像本文中提到的那样通过指定目标并且空值消失并获取正确的详细信息时,问题得到解决。
tsc -t es5 -w 应用程序 https://stackoverflow.com/a/44285244/18735323