Custom typings for external module (with classes) not recognized

Viewed 72

I am having trouble generating the correct syntax for a Typescript types file for an external CommonJS module which uses provides multiple classes. The NPM module socket.io-mock does not provide any Typescript typings to pull from so I decided to define my own as I went. The overall goal is simulating the socketio connections for testing my React App which is exclusively in Typescript. I dug through the repository code and determined all the typings necessary. This is my types file I came up with:

// 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
}

What am I doing incorrectly? How do I get vscode and more importantly the compiler to recognize the types defined and also not fail when I call?

If I don't use declare in the types file and instead just use export class. It at least compiles but then I get a error code on the new keyword when I run my test suite. This may be a red herring since based on the Typescript documentation I should be using declare as above

// 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 () => {
    // ...
  })
})

It is important that I am able to export both the SocketMock & SocketClient classes.

0 Answers
Related