typescript - 是否可以键入不是箭头函数的 TS 类方法?
问题描述
下面是我正在尝试做的一个非常简化的示例。我正在尝试使用一种方法定义来定义另一种方法定义。如果将方法转换为箭头函数,我可以做到这一点,但是当它不是箭头函数时,我想不出任何语法来键入它。这可能吗?
class A {
doThing(x: number, y: string) { return 123; }
doThingAndReturn42: typeof A.prototype.doThing = (...args) => {
this.doThing(...args);
return 42;
}
// Is it possible to type this like the above method?
doThing2AndReturn42(...args) {
this.doThing(...args);
return 42;
}
}
解决方案
最接近的是使用辅助类型Parameters
和ReturnType
:
class A {
doThing(x: number, y: string) { return 123; }
doThingAndReturn42: A['doThing'] = (...args) => {
this.doThing(...args);
return 42;
}
doThing2AndReturn42(...args: Parameters<A['doThing']>): ReturnType<A['doThing']> {
this.doThing(...args);
return 42;
}
}
请注意,写起来A['doThing']
比typeof A.prototype.doThing
.
推荐阅读
- groovy - 使用包含从列表中查找字符串无法按预期工作
- r - 如何处理r中不同长度的xts变量?
- python - 在python中向嵌套字典添加新值
- bixby - 如何在 Bixby 结果视图的图像中心显示文本?
- oracle - 为什么触发器主体中绑定变量的触发器伪记录占位符而不是何时?
- wpf - 滑块和文本框的 WPF MulitBinding 未更新属性
- r - Shinyapps:与服务器断开连接
- android - 如何使用 Okio 发出 post 请求?
- java - 休眠搜索:在索引时搜索字段的任何部分而不会丢失字段的内容
- c# - 无法在 MVC 应用程序中检索 HttpContext.Current.User