首页 > 解决方案 > 从类型中提取调用签名

问题描述

给定一个包含调用签名和附加属性的类型,例如:

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;

标签: typescript

解决方案


您可以使用内置类型来提取参数和返回类型并重建签名ReturnTypeParameters

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; 

注意:对于适用于多个重载的解决方案,请参见此处


推荐阅读