首页 > 解决方案 > 如何使用 TypeScript 在 Node.js 中扩展 WebSocket 类型?

问题描述

我正在尝试扩展以下 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

解决方案


创建一个自定义接口 -ExtWebSocket接口将扩展WebSocket。然后投你的socketas 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
  })
});

推荐阅读