WebSocket interface cannot be used in place of WebSocket?

I’m following a guide to try and set up a WebSocket.Server using ws and Express 4 with NodeJS and TypeScript. Problem is that the guide I’m following (found here: https://morioh.com/p/3b302785a62f) seems like it’s out of date or something because the code provided doesn’t work.

I’m trying to use an extended websocket object to keep track of an alive connection. It looks like this:

interface ExtWebSocket extends WebSocket {
    isAlive: boolean;

Now doing this, as the code in the tutorial shows, I get an error:

setInterval(() => {
    wss.clients.forEach((ws: ExtWebSocket) => {
        if (!ws.isAlive) return ws.terminate();
        ws.isAlive = false;
        ws.ping(null, false, true);
}, 10000);

The error states that I cannot use the ExtWebSocket in the forEach loop but I cannot figure out why?


It is because you can’t ‘de-narrow’ a WebSocket to an ExtWebSocket since it extends WebSocket. If you had an ExtWebSocket, then you could narrow it down to a WebSocket but not vice-versa.

Here is a link to the typescript handbook on this topic: https://www.typescriptlang.org/docs/handbook/2/narrowing.html