具有 return 类型的所有 class 方法名称的通用类型

Generic type for all class methods names with return type

我正在尝试创建一个泛型,它将为我提供有关所有 class 方法 return 类型(+ 字段,但它们并不那么重要)的信息。

假设我创建了这样一个 class:

class TestClass {
    testField: string;

    constructor() {
        this.testField = 'test';
    }

    testMethod1(param: number): number {
        return param;
    }

    testMethod2(param: string): string {
        return param;
    }

}

结果,我想要这样的类型:

interface TestClassMethodsNamesReturnType {
  testMethod1: number;
  testMethod2: string;
}

到目前为止我尝试了什么

你有什么提示或想法我怎样才能做到这一点?

虽然您需要使用映射类型中的 as 子句进行条件筛选,但您可以通过映射类型执行此操作。然后,检查该值是否扩展 Function 然后 return never 如果没有,那么它不会被映射。这是完整的代码:

class TestClass {
    testField: string;

    constructor() {
        this.testField = 'test';
    }

    testMethod1(param: number): number {
        return param;
    }

    testMethod2(param: string): string {
        return param;
    }

}

type FnReturns<T> = { [K in keyof T as T[K] extends Function ? K : never]: ReturnType<T[K] extends (...args: any[]) => any ? T[K] : never> };

// Correctly passes:
const foo: FnReturns<InstanceType<typeof TestClass>> = {
    testMethod1: 23,
    testMethod2: "hey",
}

// correctly fails:
const fail: FnReturns<InstanceType<typeof TestClass>> = {}

TypeScript Playground Link

另请注意我如何使用 typeof TestClassInstanceType 来获取 TestClass.

的实例方法和属性