如何从“ ws”库扩展接口WebSocket?

时间:2019-02-18 14:04:25

标签: typescript

我尝试扩展库的接口,但没有成功:(

请帮帮我! 我尝试从ws library

扩展WebSocket接口。
...
declare class WebSocket extends events.EventEmitter {
   ...
}

declare namespace WebSocket {
   ...
}

export = WebSocket;

我需要在WebSocket类中添加isAlive:布尔值

尝试:

从'ws'导入ws;

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

但没有帮助

4 个答案:

答案 0 :(得分:2)

我最初将其发布在github github上。

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

尽管这不起作用(因为WebSocket是指类,而不是声明的接口):

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

当它们这样做时:

  1. 没有类型定义:
socket.on('connection', (ws, req: http.IncomingMessage) => {
    ws.isAlive = true;
}
  1. 具有类型定义(WebSocket.WebSocket):
socket.on('connection', (ws: WebSocket.WebSocket, req: http.IncomingMessage) => {
    ws.isAlive = true;
}

答案 1 :(得分:0)

只需声明一个具有一些新属性的新类接口

declare class MyWebSocket extends WebSocket {
  online: boolean;
  ...
}

答案 2 :(得分:0)

interface WebSocket {
    online: boolean;
}

答案 3 :(得分:0)

另一个解决方法是创建一个扩展WebSocket的类并将其强制转换为它。在WebSocketEx.ts中添加:

  import WebSocket from 'ws'

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

像这样使用它:

  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)}`)
    })