【问题标题】:How can I extend WebSocket types in Node.js using TypeScript?如何使用 TypeScript 在 Node.js 中扩展 WebSocket 类型?
【发布时间】:2020-03-30 23:51:45
【问题描述】:

我正在尝试扩展以下 WebSocket https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts

无论我尝试什么,我似乎都无法向 WebSocket 添加新属性

// Messes with other typings in the WebSocket
declare module "ws" {
  // Tried declare class MyWebSocket extends WebSocket too
  interface WebSocket {
    id: string;
  }
}

wss.on("connection", socket => {
  const id = uuidv4();
  socket.id = id

  socket.on("message", data => {

我在网上看到多人遇到这个问题,但我找不到详细的解决方案

【问题讨论】:

    标签: typescript


    【解决方案1】:

    创建自定义接口-ExtWebSocket,该接口将扩展WebSocket。然后将您的socket 转换为ExtWebSocket。不需要declare module

    interface ExtWebSocket extends WebSocket {
      id: string; // your custom property
    }
    

    用法

    wss.on("connection", (socket: ExtWebSocket) => { // here
      const id = uuidv4();
      socket.id = id;
    
      socket.on("message", data => {
        // do something
      })
    });
    

    【讨论】:

    • 这给了我Property 'on' does not exist on type 'MyWebSocket'
    • 你确定MyWebSocket 扩展WebSocket
    • 原来我必须 "allowSyntheticDefaultImports": true 并导入它,否则我认为它会从 Node 中获取 WebSocket,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 2016-08-02
    • 1970-01-01
    • 2021-03-25
    • 2022-01-22
    • 2022-01-21
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多