如何使用 TypeScript 扩展 Node.js 中的 WebSocket 类型?

2024-01-19

我正在尝试扩展以下 WebSockethttps://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts 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 => {

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


创建自定义界面 -ExtWebSocket,接口将扩展WebSocket。然后投射你的socket as ExtWebSocket。不需要declare module.

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

Usage

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

  socket.on("message", data => {
    // do something
  })
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 TypeScript 扩展 Node.js 中的 WebSocket 类型? 的相关文章

随机推荐