typescript - 在 typescript 类型中引用静态方法:自动拾取方法签名
问题描述
我有一个带有静态方法的类:
class Application {
static get(): string {
...
}
}
现在我想在另一个类中引用这个静态 get 方法。我知道我可以这样做:
class Caller {
klass: { get (): typeof Application["get"] }
}
如果该方法不带参数,这很容易工作。编辑:请在下面查看为什么这是错误的
现在,如果我添加一个参数:
class Application {
static get(argument: string): string {
...
}
}
...我还必须更改Caller
(以及具有此签名的所有其他类):
class Caller {
klass: { get (argument: string): typeof Application["get"] }
}
有没有办法避免这种情况?因为很明显,klass.get
总是遵循 的函数签名Application.get
。有没有办法告诉打字稿这样的事情:
class Caller {
klass: { get (signatureof typeof Application["get"]): typeof Application["get"] }
}
编辑: 其实我刚刚意识到上面是错误的: 我实际上定义get()
返回的行为像typeof Application["get"]
。
我给了它一个新的镜头:
class Caller {
klass: {
[Key in keyof typeof Application]: typeof Application[Key]
}
}
...虽然我还没有看到这是否能解决它,brb。
编辑2:两种方式似乎都是可能的:
// reference all properties
class Caller {
klass: {
[Key in keyof typeof Application]: typeof Application[Key]
}
}
// or if only one specific thing is needed
// reference one property
class Caller {
klass: {
get: typeof Application["get"]
}
}
不幸的是,如果引用方法更复杂,例如get()
访问定义的静态属性Application
,这会变得更复杂,因为打字稿会抱怨那些没有找到(如果只引用了方法,而不是每个属性)。
所以我认为要走的路是引用所有属性以确保安全。
解决方案
您可以使用 引用静态方法的类型typeof Class['methodName']
。您可以直接将此类型用作 的类型get
:
class Caller {
klass: {
get: typeof Application["get"]
}
}
这将意味着get
与 的方法相同的get
类型 Application
。typeof Application["get"]
是方法的整个函数签名,所以对参数或返回类型的任何更改都会反映在get
onklass
推荐阅读
- amazon-web-services - AWS Elastic Beanstalk - how to stop previous docker before starting new one
- python - Python pandas 当我加载一个csv文件时,函数“iterrow”并没有真正起作用
- html - 无法摆脱滚动条
- react-native - 解析与项目根目录外的本机捆绑文件相关的资产
- amazon-web-services - 如何识别导致 AWS lambda 中的限制异常的原因以及如何处理该异常
- java - 为什么一个用户会得到 NoSuchMethodError 而成千上万的用户却没有?
- python-3.x - 如何将 PRAW 干净地集成到我的新 Reddit Bot 中?
- wordpress - 不处于编辑状态时,块预览不可见
- ubuntu - 无法安装程序
- pandas - Dask:将 dask.DataFrame 转换为 xarray.Dataset