首页 > 解决方案 > 是否可以键入不是箭头函数的 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;
    }
}

标签: typescript

解决方案


最接近的是使用辅助类型ParametersReturnType

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.

游乐场链接


推荐阅读