Adding a property to a third party class in TypeScript

I’ve been on the TypeScript gitter and this is the best we’ve come up with:

import * as express from 'express';
import * as http from 'http';
import * as WebSocket from 'ws';

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// ******* THIS IS THE IMPORTANT BIT  ********
interface WebSocketWithStatus extends WebSocket {
  isAlive?: boolean;
}

function heartbeat(this: WebSocketWithStatus) {
  this.isAlive = true;
}

function onConnection(ws: WebSocketWithStatus) {
  ws.isAlive = true;
  ws.on('pong', heartbeat);
}

wss.on('connection', onConnection);

Beats (ws as any).isAlve but it feels like there should be something better.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.