Vadim
Vadim

Reputation: 3794

How to extend interface WebSocket from 'ws' library?

I try to extend an interface of a library but without success :(

Help me please! I try to extend WebSocket interface from ws library

...
declare class WebSocket extends events.EventEmitter {
   ...
}

declare namespace WebSocket {
   ...
}

export = WebSocket;

I need to add isAlive: boolean to WebSocket class

Try to:

import ws from 'ws';

declare module 'ws' {
    export interface WebSocket {
        isAlive: boolean;
    }
}

but it does not help

Upvotes: 2

Views: 979

Answers (3)

Zmey
Zmey

Reputation: 2559

Another workaround is to create a class which extends WebSocket and cast to it. In WebSocketEx.ts add:

  import WebSocket from 'ws'

  export default interface WebSocketEx extends WebSocket {
    myProperty?: string
  }

Use it like this:

  import WebSocketEx from './WebSocketEx'

  fastify.get('/', { websocket: true }, function wsHandler(connection, req) {
    const socket = connection.socket // This is original WebSocket
    const socketEx = (socket as unknown) as WebSocketEx

    socketEx.myProperty = 'abcdef'

    socketEx.on('message', (message) => {
      log(`WS: message: ${JSON.stringify(message)}`)
    })

Upvotes: 0

Binier
Binier

Reputation: 1107

I originally posted it on github github.

declare module "ws" {
  class _WS extends WebSocket { }
  export interface WebSocket extends _WS {
      isAlive: boolean;
  }
}

though this will not work (since WebSocket here refers to the class, not the declared interface):

socket.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
    ws.isAlive = true;
}

while these do:

  1. without type definition:
socket.on('connection', (ws, req: http.IncomingMessage) => {
    ws.isAlive = true;
}
  1. with type definition (WebSocket.WebSocket):
socket.on('connection', (ws: WebSocket.WebSocket, req: http.IncomingMessage) => {
    ws.isAlive = true;
}

Upvotes: 2

Vadim
Vadim

Reputation: 3794

interface WebSocket {
    online: boolean;
}

Upvotes: -1

Related Questions