The WebSocket objects which ws uses are not assignable to the typescript WebSocket type because the dispatchEvent method is missing from the implementation.
Create a ws server
Listen for the connection event
Pass the websocket passed to the connection handler to a typescript function which expects a WebSocket object.
No typechecking errors occur
src/connection/__tests__/socket.ts:104:33 - error TS2345: Argument of type 'WebSocket' is not assignable to parameter of type 'Socket'.
Property 'dispatchEvent' is missing in type 'WebSocket' but required in type 'WebSocket'.
104 resolve(new SocketProxy(socket, storage));
~~~~~~
../../node_modules/typescript/lib/lib.dom.d.ts:5226:5
5226 dispatchEvent(event: Event): boolean;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'dispatchEvent' is declared here.
There is no TypeScript on this project and there is no dispatchEvent() because we don't fully implement the EventTarget interface.
There is no TypeScript on this project
Understood! I鈥檓 using the types from https://www.npmjs.com/package/@types/ws
there is no dispatchEvent() because we don't fully implement the EventTarget interface.
A stub method which throws a not implemented error would be enough to satisfy the type definition.
A stub method which throws a not implemented error would be enough to satisfy the type definition.
Please file a PR if you are interested in having it.
I encountered this issue as well. In my case, I have an interface that contains:
ws: WebSocket;
By default, TS assumes you mean the definition in _lib.dom.d.ts_. Since the only WebSocket I cared about was the class declaration defined in the @types/ws package, I added the following at the top of the file containing my interface:
import WebSocket from 'ws';
This explicit import overrides the "default" one. If you are already importing other stuff from 'ws', you can do:
import WebSocket, { Server /* etc */} from 'ws';
(note: I am using @types/ws version 7.4.0.)
Most helpful comment
Please file a PR if you are interested in having it.