0

I'm trying to extend a class (from an external websocket library) with a custom function by adding my function to the prototype. But i'm get the Property 'customFuction' does not exist on type 'WebSocket' error which is understandable.

import WebSocket from "ws";

WebSocket.prototype.customFunction = function customFunction(): void {
                    ^^^^^^^^^^^^^^
"Property 'customFuction' does not exist on type 'WebSocket'
};

But my question is how do I add my function to the existing class definition?
I don't want to create a new type (like MyWebSocket extends WebSocket) because I want the method to be available on the WebSocket class.


Edit: I also tried the solution below suggested by @Balastrong but this still doesn't work. I'm also using the @types/ws package for the type definitions but I don't think module augmentation updates those definitions, could this be the reason for why this solution isn't working?

// WebSocketExtensions.ts
import WebSocket from "ws";

declare module "ws" {
  export interface WebbSocket {
    customFunction(): void;
  }
}

WebSocket.prototype.customFunction = () => console.log('Hey');
2
  • WebSocket is the default export of the ws module. Your augmented module declares an additional named export. Commented Sep 28, 2021 at 20:59
  • Probably you just need to remove the export keyword (and fix the misspelling), so that interface WebSocket extends the declaration from github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/… Commented Sep 28, 2021 at 21:02

1 Answer 1

1

Typescript allows to merge interfaces so that if there are multiple interfaces with the same name, they're merged as if they were one.

You can declare your method to a WebSocket interface inside a declare global, then you can add your prototype.

declare global {
  export interface WebSocket {
    customFunction: () => void;
  }
}

WebSocket.prototype.customFunction = () => console.log('Hey');

If you get an error on global like Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.ts(2669) you need to add export {}; at the beginning of the file.

Sign up to request clarification or add additional context in comments.

3 Comments

OP doesn't modify the global WebSocket available in browsers, they extend the export of the ws library
…but yes, declaration merging is the way to go, in particular typescriptlang.org/docs/handbook/…
I tried you suggestion (see updated question) but it still doesn't work. I'm also using @types/ws for the type definitions for ws could this be the reason why I cant augment the WebSocket class?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.