当有多个可用时,打字稿使用不正确的类型开玩笑

Cha*_*wis 8 javascript typescript jestjs js-cookie

我是打字稿的新手,注意到了我没想到的行为。当我使用js-cookie包模拟命名导入时,它模拟了该属性的特定实例,但错误地选择了要使用的正确类型。

import Cookies from "js-cookie"
import { mocked } from "ts-jest/utils"

jest.mock("js-cookie")
const mockedCookies = mocked(Cookies, true)

beforeEach(() => {
  mockedCookies.get = jest.fn().mockImplementation(() => "123")
})

it("SampleTest", () => {
  //this line throws an error as it is using a difference interface to check against
  mockedCookies.get.mockImplementationOnce(() => undefined)
  //continue test...
}
Run Code Online (Sandbox Code Playgroud)

@types/js-cookies有此两种定义,它总是使用get()时,我引用它的版本mockCookie.get.<some-jest-function>。因此,我收到打字稿错误说Type 'undefined' is not assignable to type '{ [key: string]: string; }'..

/**
* Read cookie
*/
get(name: string): string | undefined;

/**
* Read all available cookies
*/
get(): {[key: string]: string};
Run Code Online (Sandbox Code Playgroud)

我可以通过jest.fn()每次都重新声明来解决这个问题,但更喜欢使用方便的 jest 函数(如 mockImplementationOnce)。

难道我做错了什么?有没有办法强制get使用哪种类型?

Jun*_*Gan 1

我不确定这是否有帮助,但您mockedCookies.get.mockImplementationOnce(() => ({}))现在可以使用它来消除此错误。

更新:经过一些测试,我发现这些模拟函数以字典样式格式存储。最后一个同名的函数总是替换前面的函数。

如果您尝试从“js-cookie”移动到get(name: string)下面get(),您将看到此错误消失了。所以没有办法获得同名的特定函数。