看着
the types from
@types/jest
,它扩展了函数,但带有特定的调用签名:
interface Mock<T = any, Y extends any[] = any>
extends Function, MockInstance<T, Y> {
new (...args: Y): T;
(...args: Y): T; // <--
}
fn()
刚回来
Mock
因为默认的返回类型(
T
)是吗
any
,这是允许的。
fn
可以使用类型参数调用,以显式指定返回类型,或者更方便的是,可以从实现函数推断类型:
function fn<T, Y extends any[]>(implementation?: (...args: Y) => T): Mock<T, Y>;
例子:
// Identifies wrong return type (Type 'void' is not assignable to type 'string')
myClass.myFunction = jest.fn(() => { })
// Correct return type
myClass.myFunction = jest.fn(() => '')
Playground
如果使用jest包本身的类型,则
jest.fn()
如果没有其他内容,也会产生错误,因为它返回
Mock<UnknownFunction>
.
Playground