Reputation: 3794
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
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
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:
socket.on('connection', (ws, req: http.IncomingMessage) => {
ws.isAlive = true;
}
WebSocket.WebSocket
):socket.on('connection', (ws: WebSocket.WebSocket, req: http.IncomingMessage) => {
ws.isAlive = true;
}
Upvotes: 2