stomp-js / stompjs

Javascript and Typescript Stomp client for Web browsers and node.js apps
Apache License 2.0
738 stars 80 forks source link

TypeScript 5 claims IStompSocketMessageEvent and MessageEvent are incompatible #619

Open bes opened 6 months ago

bes commented 6 months ago

Hello,

I recently decided to upgrade to stompjs 7 from 5.4.4, and typescript doesn't like the following code:

        client.webSocketFactory = (): WebSocket => {
            return new WebSocket(myBrokerUrl);
        };

The compiler error is the following:

TS2322: Type '() => WebSocket' is not assignable to type '() => IStompSocket'.
  Call signature return types 'WebSocket' and 'IStompSocket' are incompatible.
    The types of 'onmessage' are incompatible between these types.
      Type '((this: WebSocket, ev: MessageEvent<any>) => any) | null' is not assignable to type '((ev: IStompSocketMessageEvent) => any) | null | undefined'.
        Type '(this: WebSocket, ev: MessageEvent<any>) => any' is not assignable to type '(ev: IStompSocketMessageEvent) => any'.
          Types of parameters 'ev' and 'ev' are incompatible.
            Type 'IStompSocketMessageEvent' is missing the following properties from type 'MessageEvent<any>': lastEventId, origin, ports, source, and 23 more.

It seems that my typescript configuration expects IStompSocketMessageEvent to contain a lot more fields than data?: string | ArrayBuffer; to be compatible with MessageEvent from lib.dom.d.ts.

How can I work around this issue?

bes commented 6 months ago

Changing the return type doesn't help either:

        client.webSocketFactory = (): IStompSocket => {
            return new WebSocket(myBrokerUrl);
        };
TS2322: Type 'WebSocket' is not assignable to type 'IStompSocket'.
  Types of property 'onmessage' are incompatible.
    Type '((this: WebSocket, ev: MessageEvent<any>) => any) | null' is not assignable to type '((ev: IStompSocketMessageEvent) => any) | null | undefined'.
      Type '(this: WebSocket, ev: MessageEvent<any>) => any' is not assignable to type '(ev: IStompSocketMessageEvent) => any'.
        Types of parameters 'ev' and 'ev' are incompatible.
          Type 'IStompSocketMessageEvent' is missing the following properties from type 'MessageEvent<any>': lastEventId, origin, ports, source, and 23 more.
bes commented 6 months ago

This works, but feels a bit icky:

        client.webSocketFactory = (): IStompSocket => {
            return new WebSocket(myBrokerUrl) as IStompSocket;
        };

I would rather not cast with as if I can avoid it.

kum-deepak commented 2 months ago

Currently I guess your workaround is alright. I can look at a better fix when I upgrade this library build to use Typescript 5.