Typescript 在简单装饰器中保留方法签名

Typescript 在简单装饰器中保留方法签名,typescript,Typescript,也许有人可以建议,我实现了一个简单的装饰器,它接受方法,添加一些逻辑并返回具有相同签名的方法 type Method = (...args: any[]) => Promise<any> const useBusy = <T extends Method>(method: T): [boolean, T] => { const [isBusy, setIsBusy] = useState(false); const wrappedMethod =

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

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;
type-Method=(…args:any[])=>Promise
const useBusy=(方法:T):[boolean,T]=>{
const[isBusy,setIsBusy]=useState(false);
const wrappedMethod=async(…args:any[])=>{
setIsBusy(true);
const result=wait method.apply(这是args);
setIsBusy(假)
返回结果;
}
return[isBusy,wrappedMethod为T];
}
导出默认的useBusy;
是否可以执行相同的操作,但不使用数组返回对象{IsBusy,method}?但我希望保留传递的方法的名称,例如,如果我执行以下操作:

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


可能吗?

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

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

您将得到一个名称冲突
myMethod
在定义之前存在,您将再次定义它。也就是说,您无法访问传入参数的名称。。最好是对输入对象进行分解,并进行类似于
useBusy({myMethod})
的调用。
const busy = useBusy({myMethod});
const isBusy = busy.isBusy;
const myBusyMethod = busy.myMethod;