3

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

1 Answer 1

7

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
  })
});
Sign up to request clarification or add additional context in comments.

4 Comments

This gives me Property 'on' does not exist on type 'MyWebSocket'
Are your sure MyWebSocket extends WebSocket
Turns out I had to "allowSyntheticDefaultImports": true and import it, otherwise it picked up the WebSocket from Node I think, thanks!
In order to stop TypeScript complaining about the wss.handleUpgrade callback I had to add the type to the server, like this: private wss = new Server<ExtWebSocket>({port: 3033})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.