我有以下方法(没有类型,因为这是这个问题的意思):
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
。
答案 0 :(得分:2)
您应该为此使用通用类型参数:
function mock<T>(selector: () => T, returnValue: T) {
}
这样,您可以“连接”选择器函数的返回类型和returnValue参数。