【问题标题】:Property 'prototype' does not exist属性“原型”不存在
【发布时间】:2018-07-05 21:21:24
【问题描述】:

我正在尝试在打字稿中使用jest 和模拟ioredis

问题是我收到来自typescript 的错误:

tests/__mocks__/ioredis.ts(5,9): error TS2339: Property 'prototype' does not exist on type 'Redis''

代码确实有效,但我想解决这个错误。 这是我的模拟:

// tests/__mocks__/ioredis.ts
import { Redis } from 'ioredis';

const IORedis: Redis = jest.genMockFromModule<Redis>('ioredis');

IORedis.prototype.hgetall = jest.fn().mockImplementation(async (key: string) => {
    // Some mock implementation
});

module.exports = IORedis;

我做错了什么?

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    没有完美的解决方案。

    首先定义一个带有原型属性的接口:

    interface IPrototype { prototype: any; }
    

    像这样使用 IORedis 来访问原型和其他 Redis 方法。

    (IORedis as IPrototype & Redis).prototype ...
    

    另一种选择可能是这样声明您的 const:

    interface IPrototype { prototype: any; }
    type MyRedis = Redis & IPrototype;
    const IORedis: MyRedis = jest.genMockFromModule<MyRedis>('ioredis');
    

    希望有帮助!

    【讨论】:

      【解决方案2】:

      如果需要扩展的类型是泛型,可以在创建联合类型时使用类型变量。

      interface IPrototype { prototype: any; }
      type ExtendedType<A, B> = IPrototype & BasicType<A, B>;
      

      然后你就可以使用了

      (myvar as ExtendedType<any, any>).prototype
      

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2016-03-29
        • 2021-01-09
        • 1970-01-01
        • 2021-07-10
        • 2022-01-07
        • 2022-01-27
        • 2023-03-18
        相关资源
        最近更新 更多