user13103906
user13103906

Reputation:

How can I extend WebSocket types in Node.js using TypeScript?

I am trying to extend the following WebSocket https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/index.d.ts

Whatever I try, I cannot seem to add a new property to the 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 => {

I saw multiple people having this issue online but I could not find a detailed solution

Upvotes: 3

Views: 3500

Answers (1)

hoangdv
hoangdv

Reputation: 16137

Create a custom interface - ExtWebSocket, the interface will extend WebSocket. Then cast your socket as ExtWebSocket. No need 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
  })
});

Upvotes: 7

Related Questions