首页 > 解决方案 > 在简单装饰器中保留方法签名

问题描述

也许有人可以建议,我实现了一个简单的装饰器,它接受方法,添加一些逻辑并返回具有相同签名的方法。

type Method = (...args: any[]) => Promise<any>

 const useBusy = <T extends Method>(method: T): [boolean, T] => {
  const [isBusy, setIsBusy] = useState(false);
  const wrappedMethod = async (...args: any[]) => {
    setIsBusy(true);
    const result = await method.apply(this, args);
    setIsBusy(false)

    return result;
  }

  return [isBusy, wrappedMethod as T];
}

export default useBusy;

是否可以做同样的事情,而不是数组返回对象 {IsBusy,方法}?但我想保留传递方法的名称,例如,如果我执行以下操作:

const {isBusy, myMethod} = useBusy(myMethod) 我希望打字稿检查响应名称,只允许 isBusy 和 myMethod 。

可能吗?

标签: typescript

解决方案


您不能绑定到传递对象的名称。您可以做的是获取一个对象作为输入,并输出该对象的扩展版本作为输出。

const useBusy = <T extends { [k in keyof T]: Method }>(methodObj: T): T & { isBusy: boolean } => {
 ...
}

然后你可以这样做:

const busy = useBusy({myMethod});
const isBusy = busy.isBusy;
const myBusyMethod = busy.myMethod;

操场


推荐阅读