typescript - 从类型中提取调用签名
问题描述
给定一个包含调用签名和附加属性的类型,例如:
export interface Foo<T> {
(arg: T): T;
doFoo(): void;
}
我们如何键入一个实现这种类型的调用签名的函数?
// Property 'doFoo' is missing in type '(arg: string) => string'
// but required in type 'Foo<string>'.
const foo: Foo<string> = (arg: string) => arg;
排除调用签名的一种方法是使用映射类型,因为调用签名将不在keyof Foo<T>
:
type FooProperties<T> = { [K in keyof Foo<T>]: Foo<T>[K] };
const foo: FooProperties<string> = {
doFoo() {}
};
但是我们怎样才能得到相反的结果,那就是只有调用签名,所以我们可以编写以下内容?
type FooSignature<T> = /* …? */
const foo: FooSignature<string> = (arg: string) => arg;
解决方案
您可以使用内置类型来提取参数和返回类型并重建签名ReturnType
:Parameters
export interface Foo<T> {
(arg: T): T;
doFoo(): void;
}
type JustSignature<T extends (...a: any[]) => unknown> = (...a: Parameters<T>) => ReturnType<T>
type FooSignature<T> = JustSignature<Foo<T>>
const foo: FooSignature<string> = (arg: string) => arg;
注意:对于适用于多个重载的解决方案,请参见此处
推荐阅读
- python - dataframe.iloc[:;:] 和 datafrane.iloc[:,:] .values 有什么区别
- scala - 将 Set 转换为 Scala Spark 中的单个对象
- javascript - 无法在 MacOS 10.13.2 上设置 Reaction Commerce
- python - 如何为不泄漏内存的大型生成器编写消费者?
- python - 如何将模块的属性添加到具有自定义行为的类
- azure - 使用 Postman 在 Azure 上发出 500 内部服务器错误 POST 请求
- java - 无法在我的依赖项中实现 'com.firebaseui:firebase-ui-auth:2.3.0'
- python - 如何让 arff.loadarff 与 urllib.request 一起从 URL 读取 arff 文件?
- ruby-on-rails - 基于关联的 Rails
- html - 我的代码中的 CSS 对齐有什么问题