基于先前参数返回类型的方法参数类型

时间:2020-08-27 13:09:13

标签: typescript

我有以下方法(没有类型,因为这是这个问题的意思):

export const mockSelector = (selector, matchers, returnValue) => {
    // Implementation
}

在此方法中,selector是一种返回值的方法,而returnValue是我要配置的模拟返回值。它的用法如下:mockSelector(timerStoppedAtForPlayerSelector, [player.id, timerType], null)

我的问题的核心是:无论returnValue的返回类型是什么,我该如何确定selector的类型?换句话说,如果我要嘲笑的选择器是() => 'Hello',那么如果为string给出returnValue以外的任何内容,并且选择器为() => 42,则TS将会出错。那么如果returnType不是number,TS就会出错。

我曾考虑过使用泛型来键入参数,但是我遇到的问题是,每当selector的签名更改时,TS都不会警告我。

这是我想得到的最接近的东西:

export const mockSelector = (selector: <T>(...args: any[]) => T, matchers: unknown[], returnValue: ReturnType<typeof selector>) => {
    // Implementation
}

但是,使用它会导致以下错误:TS2345 Argument of type A is not assignable to parameter of type A

1 个答案:

答案 0 :(得分:2)

您应该为此使用通用类型参数:

function mock<T>(selector: () => T, returnValue: T) {

}

这样,您可以“连接”选择器函数的返回类型和returnValue参数。