代码之家  ›  专栏  ›  技术社区  ›  hikky36

为什么开玩笑。fn()可以分配给Typescript中的任何函数?

  •  0
  • hikky36  · 技术社区  · 4 年前

    我不知道怎么开玩笑。fn()在Typescript中工作。例如

    class MyClass {
      myFunction() {
        return 'hello'
      }
    }
    
    let myClass = new MyClass()
    myClass.myFunction = jest.fn()
    

    据我所知,我的班级。myFunction的类型为“()=>但是开玩笑。fn()返回一个“Mock”。我注意到“Mock”实际上是对“Function”的扩展,但Function没有那么具体()=>那这怎么行呢?

    1 回复  |  直到 4 年前
        1
  •  1
  •   brunnerh    4 年前

    看着 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

    推荐文章