What are the steps to expand the WebSocket interface using the 'ws' library?

I am struggling to extend an interface in a library and I need some help. I am trying to extend the WebSocket interface from the ws library.

...
declare class WebSocket extends events.EventEmitter {
   ...
}

declare namespace WebSocket {
   ...
}

export = WebSocket;

In particular, I need to add a property called isAlive of type boolean to the WebSocket class.

I have tried:

import ws from 'ws';

declare module 'ws' {
    export interface WebSocket {
        isAlive: boolean;
    }
}

but so far it has not been successful.

Answer №1

This information was originally shared on my Github page here.

declare module "ws" {
  class _WS extends WebSocket { }
  export interface WebSocket extends _WS {
      isOnline: boolean;
  }
}

It's worth noting that the following code snippet will not function as intended, given that WebSocket refers to the class rather than the declared interface:

socket.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
    ws.isOnline = true;
}

However, these alternatives will work correctly:

  1. Without specifying a type:
socket.on('connection', (ws, req: http.IncomingMessage) => {
    ws.isOnline = true;
}
  1. With type definition (WebSocket.WebSocket):
socket.on('connection', (ws: WebSocket.WebSocket, req: http.IncomingMessage) => {
    ws.isOnline = true;
}

Answer №2

To overcome this issue, one possible solution is to define a new class that extends WebSocket and then convert the original WebSocket instance to this new class. Create a file named WebSocketEx.ts with the following content:

  import WebSocket from 'ws'

  export default interface WebSocketEx extends WebSocket {
    myProperty?: string
  }

You can then use it in your code like so:

  import WebSocketEx from './WebSocketEx'

  fastify.get('/', { websocket: true }, function wsHandler(connection, req) {
    const socket = connection.socket // This is the regular WebSocket object
    const socketEx = (socket as unknown) as WebSocketEx

    socketEx.myProperty = 'abcdef'

    socketEx.on('message', (message) => {
      log(`WS: message: ${JSON.stringify(message)}`)
    })

Answer №3

class SocketConnection {
    isOnline: boolean;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NestJS Exporting: Establishing a connection for PostgreSQL multi tenancy

I have been working on implementing a multi tenancy architecture using postgres. The functionality is all in place within the tenant service, but now I need to import this connection into a different module called shops. Can anyone provide guidance on how ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

What is the process for importing a TypeScript module exclusively through typings without having to download it separately?

Currently, I am working on a widget for a website that is already utilizing jQuery and I am using TypeScript. The goal is to embed my output into the host website while taking advantage of the existing jQuery library loaded by the host site. In order to r ...

What sets apart extending and intersecting interfaces in TypeScript?

If we have the following type defined: interface Shape { color: string; } Now, let's explore two different methods to add extra properties to this type: Using Extension interface Square extends Shape { sideLength: number; } Using Intersection ...

Setting up ESLint and Prettier with TypeScript on Node 20: A Guide

I attempted to set up Prettier with ESLint and crafted a configuration in settings.json to rectify errors upon saving, but the errors only manifest in .js files and not .ts files. How can I adjust this? Dependencies: "@eslint/js": "^9.4.0& ...

Sort the observable data by a value returned from an API request

I am completely new to using RxJS and any assistance offered would be greatly appreciated! Within my component's HTML template, I am looking to create a radio button list. The values for this list are fetched from an observable using the async pipe. ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

The 'string[]' type cannot be assigned to the 'string | ParsedUrlQueryInput | null | undefined' type in Next.js and Typescript

I'm facing an issue while attempting to transfer an array of strings from one page to another in Next.js using <Link href={{ pathname: "/model", query: data }}>. The problem arises when the query parameter is red underlined: Type &apos ...

Loading fonts using next.js and style jsx

I've recently started the process of converting my create react app to next.js. As a reference, I've been using Vercel's open source Next.js website to help me structure my own. In order to implement custom fonts, I created a font.ts file an ...

I'm having trouble with my Typescript file in Vscode - every time I try to edit the css code, all the text turns red. Can someone

Check out this visual representation: [1]: https://i.stack.imgur.com/9yXUJ.png Followed by the corresponding code snippet. export const GlobalStyle = createGlobalStyle` html { height: 100%; } body { background-image: url(${BGImage}); ba ...

Error in VS Code related to Vue Array Prop JSDoc TypeScript: The properties of type 'ArrayConstructor' are not found in type 'MyCustomType[]'

After reading the article "Why I no longer use TypeScript with React and why you might want to switch too", I decided to work on a Vue CLI project using ES6 without TypeScript. Instead, I enabled type checking in Visual Studio Code by utilizing JSDoc / @ty ...

Encountered an error with API request while utilizing Cashfree in a React Native environment

I'm currently integrating cashfree into my react native app for processing payments. Here is a snippet of the code I'm using: import { CFPaymentGatewayService, CFErrorResponse, } from 'react-native-cashfree-pg-sdk'; import { CFDr ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Incorporating an Ionic application into a Rails 4 application

Seeking guidance on integrating an Ionic 2/3 app with a complex Rails 4 app. What would be the optimal approach for this task? How can I seamlessly add an API to an already intricate application? ...

What is the most effective method for obtaining the ViewContainerRef of a mat-row in Angular 4

I am currently working with a mat-table and I'm looking to retrieve the ViewContainerRef of a clicked row in order to add another component within that specific row. Can anyone suggest the most effective method to obtain the ViewContainerRef of a row? ...

Tips for properly handling a property that receives its value from a callback function and waiting for it to be updated

Below is my TypeScript code: private getInfoSystem = () => { this.systemInfo = { cpuSpeed: 0 , totalRam: os.totalmem(), freeRam: os.freemem(), sysUpTime: os_utils.sysUptime(), loadAvgMinutes: { on ...

Is it possible to directly parse a multipart/mixed response without needing to first convert it into a string?

My current challenge involves receiving a multipart/mixed response over HTTP that includes JSON data and PDFs in byte format. Due to Angular's limitations with handling such responses, I have resorted to converting the response into a string using the ...

The error message "TypeScript reflect-metadata Cannot find name 'Symbol'" indicates that TypeScript is unable to locate

While browsing through http://www.typescriptlang.org/docs/handbook/decorators.html#class-decorators, I encountered an issue where it could not find the Symbol. I was unsure whether this is related to the usage of reflect-metadata or if it was previously in ...