提问人:goodkat 提问时间:10/17/2022 最后编辑:Peter Mortensengoodkat 更新时间:12/31/2022 访问量:137
有没有办法使用 TypeScript 装饰器更改返回值?
Is there a way to change the return value with a TypeScript decorator?
问:
我正在尝试改变各种方法的行为。该行为包括检查发送的参数中是否存在值,并在该方法返回的值上设置属性。
例:
function ParseDiscounts {
return function (
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
if(args[0].discounts !== undefined) {
/**
*
* here is where supposed to add a property on the return
* something like resultToBeParsed.isDiscountApplied = true
*
* */
}
const result = await originalMethod.apply(this, args);
return result;
};
return descriptor;
};
}
class Order {
@ParseDiscounts()
createOrder(discountPayload) {
/**
* Do everything that it is supposed to do while only at the return of the function
* the `isDiscountApplied = true` is added to the result through the decorator
* */
return resultToBeParsed
}
}
const firstOrder = new Order()
const firstResult = firstOrder.createOrder({ otherProperties: 'blah, blah, blah', discounts: [1,2,3]})
// firstResult.isDiscountApplied = true
const secondOrder = new Order()
const secondResult = secondOrder.createOrder({ otherProperties: 'blah, blah, blah'})
// secondResult.isDiscountApplied = false
当有任何折扣 whithin discountPayload 时,我希望添加一个属性resultToBeParsed
isDiscountApplied = false (e.g.)
我知道我可以做一些事情,比如创建一个 whithin 装饰器并分配结果 whithin,但我也想操纵方法返回周期(我什至不知道这是否可能)。parsedResponse
我不知道这是否是最好的方法,真的,如果你们知道更好的东西,我会很高兴听到......我这样做是因为有很多地方我会使用它。
答: 暂无答案
上一个:如果 alpha
下一个:Golang:调用嵌入类型的方法
评论