typescript - 在简单装饰器中保留方法签名
问题描述
也许有人可以建议,我实现了一个简单的装饰器,它接受方法,添加一些逻辑并返回具有相同签名的方法。
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 。
可能吗?
解决方案
您不能绑定到传递对象的名称。您可以做的是获取一个对象作为输入,并输出该对象的扩展版本作为输出。
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;
推荐阅读
- javascript - 在 View .NET CORE MVC 中动态显示组件和数据
- github - 如何删除从我的 github 存储库构建的 Cloudflare 页面?
- python - 如何检查 Amazon S3 存储桶中的文件夹是否为空?- boto3 蟒蛇
- grep - 如何 grep 以获取具有特定格式的多行,但如果其中一行具有特定单词,则不包含这些行作为结果
- javascript - 你可以解释吗?
- vue.js - 运行“vue 升级”时出现“无法解决依赖关系”错误
- android - 如何处理房间关系、嵌入列表和实时数据?
- django - Django 模型实例缓存 - 相同的记录
- sqlite - 序列化 R 对象并将其保存到 sqlite3 数据库
- javascript - 为什么我的 jquery 方法 window.onload() 不起作用?