gpt4 book ai didi

Typescript 装饰器 - 接受的参数太少,无法在此处用作装饰器

转载 作者:行者123 更新时间:2023-12-05 06:16:40 25 4
gpt4 key购买 nike

我正在尝试编写一个装饰器,它接受一个方法并在该方法未在指定超时(使用方法参数指定)内完成时抛出错误。不指定超时应该导致方法运行,就好像参数不存在一样。

export const setMethodTimeout = (): Function => {
return function(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
const context = this;
const args: DecoratorArgumentType = arguments;
if (args.timeout) {
const timer = setTimeout(() => {
throw new Error('The method did not finish before the specified timeout.');
}, args.timeout);
const originalMethod = descriptor.value;
descriptor.value = function() {
originalMethod
.apply(context, args)
.then((result: any) => {
clearTimeout(timer);
return result;
})
.catch((e: Error) => {
throw e;
});
};
}
return descriptor;
};
};

现在当我尝试在我的类方法上使用这个装饰器时:

@setMethodTimeout
public async getMap(params: GetMapParams, api: ApiType, reqConfig?: RequestConfiguration): Promise<Blob> {
//...
}

我收到以下 typescript 错误:

‘setMethodTimeout’ accepts too few arguments to be used as a decorator here. Did you mean to call it first and write ‘@setMethodTimeout()’?

为什么会这样?

最佳答案

它需要一个函数调用,因为您要用附加函数 setMethodTimeout 包装装饰器。如果您像这样删除它,它将在没有函数调用语法的情况下工作:

export const function setMethodTimeout(target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) {
const context = this;
const args: DecoratorArgumentType = arguments;
if (args.timeout) {
const timer = setTimeout(() => {
throw new Error('The method did not finish before the specified timeout.');
}, args.timeout);
const originalMethod = descriptor.value;
descriptor.value = function() {
originalMethod
.apply(context, args)
.then((result: any) => {
clearTimeout(timer);
return result;
})
.catch((e: Error) => {
throw e;
});
};
}
return descriptor;
};

关于Typescript 装饰器 - 接受的参数太少,无法在此处用作装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62000429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com