我无法为使用提供多个类的外部 CommonJS 模块的 Typescript 类型文件生成正确的语法。 NPM 模块 socket.io-mock
不提供任何可从中提取的 Typescript 类型,因此我决定自己定义。总体目标是模拟 socketio 连接以测试我的 React 应用程序,该应用程序仅在 Typescript 中。我挖掘了存储库代码并确定了所有必要的类型。这是我想出的类型文件:
// FILE: socketio-mock.d.ts
// Import implementation
import "socket.io-mock"
declare module "socket.io-mock" {
export = SocketMock
export = SocketClient
declare class Emitter {
constructor(obj?: Partial<Emitter>): Emitter
_callbacks: { [event: string]: Function[] }
on: (event: string, callback: (payload?: unknown) => void) => Emitter
off: (event?: string, fn?: Function) => Emitter
// ...
}
declare class SocketClient extends Emitter {
constructor(socketMock: SocketMock): SocketClient
connected: boolean
disconnected: boolean
emit: (eventKey: string, payload?: unknown, ack?: () => void) => void
disconnect: () => SocketClient
// ...
}
declare class SocketMock extends Emitter {
constructor(): SocketMock
joinedRooms: string[]
emit: (eventKey: string, payload?: unknown) => void
// ...
}
export default SocketMock
}
我做错了什么?我如何让 vscode,更重要的是让编译器识别定义的类型并且在我调用时也不会失败?
如果我不在类型文件中使用声明而是使用 export class
。它至少可以编译,但是当我运行测试套件时,我会在 new 关键字上收到错误代码。这可能是一个红鲱鱼,因为基于 Typescript documentation 我应该使用上述声明
// FILE: App.test.tsx
import { SocketMock, SocketClient } from "socket.io-mock"
describe("<App />", () => {
beforeEach(() => {
const fakeServerSocket: SocketMock = new SocketMock()
// ^
// TypeError: _socket2.SocketMock is not a constructor
// ...
})
it("renders correctly", async () => {
// ...
})
})
能够导出 SocketMock 和 SocketClient 类非常重要。