it seems isAlive property is missing from WebSocket type. see this: https://github.com/websockets/ws#how-to-detect-and-close-broken-connections
The isAlive property is being dynamically added to the ws instance in the listed example. That property isn't provided by the library.
how does one add this property to the WebSocket declaration?
I have tried all sorts of things to get this to work.
import express from 'express';
import expressWS from 'express-ws';
import WebSocket from 'ws';
declare global {
class WebSocket {
isAlive: boolean;
}
}
doesn't work. how is this supposed to work?
@Spongman Instead of declaring it globally, try this:
declare module "ws" {
interface WebSocket {
isAlive: boolean;
}
}
You can read more about it here: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
All you have to do is declare this in your file:
interface ExtWebSocket extends WebSocket {
isAlive: boolean;
}
then wherever you're defining that, for example:
setInterval(() => {
wss.clients.forEach((ws: WebSocket) => {
const extWs = ws as ExtWebSocket;
if (!extWs.isAlive) return ws.terminate();
extWs.isAlive = false;
ws.ping(null, undefined);
});
}, 10000);
You cannot augment it via a module, as this particular library implements it using a class and not an interface.
This uses type assertion: https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html
Most helpful comment
All you have to do is declare this in your file:
then wherever you're defining that, for example:
You cannot augment it via a module, as this particular library implements it using a class and not an interface.
This uses type assertion: https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html