Search code examples
typescriptvue.jssignalr

I'm trying to implement SignalR in my Vue project and i have a problem


I'm using Vue + ts and I want to implement SignalR in my project. I have read the @dreamonkey/vue-signalr documentation on how to use SignalR.

import { VueSignalR } from '@dreamonkey/vue-signalr';
import { HubConnectionBuilder } from '@microsoft/signalr';
import { createApp } from 'vue';
import App from './App.vue';

// Create your connection
// See https://docs.microsoft.com/en-us/javascript/api/@microsoft/signalr/hubconnectionbuilder
const connection = new HubConnectionBuilder()
  .withUrl('http://localhost:5000/signalr')
  .build();

**createApp(App).use(VueSignalR, { connection }).mount('#app');**

I have used this code, but i have got an error:

No overload matches this call.
  Overload 1 of 2, '(plugin: Plugin<[options: VueSignalRConfig]>, options: VueSignalRConfig): App<Element>', gave the following error.
    Argument of type '{ connection: HubConnection; }' is not assignable to parameter of type 'VueSignalRConfig'.
      Type '{ connection: HubConnection; }' is missing the following properties from type 'VueSignalRConfig': autoOffInsideComponentScope, failFn
  Overload 2 of 2, '(plugin: Plugin<[options: VueSignalRConfig]>, options: [options: VueSignalRConfig]): App<Element>', gave the following error.
    Object literal may only specify known properties, and 'connection' does not exist in type '[options: VueSignalRConfig]'.ts(2769)

I have no idea how to fix it.


Solution

  • The VueSignalRConfig type is defined as below :

    export interface VueSignalRConfig {
      connection: HubConnection;
      autoOffInsideComponentScope: boolean;
      failFn: (error: any) => void;
    }
    

    The above type has 3 required properties, providing just connection doesn't satisfy its type. What you can do is 1) provide all properties with some values 2) Cast it to the desired type or any

    createApp(App).use(VueSignalR, { 
           connection,
           autoOffInsideComponentScope: false,       
           failFn: e=> console.log(e) }).mount('#app')
    

    or

    createApp(App).use(VueSignalR, { connection } as VueSignalRConfig).mount('#app') // import VueSignalRConfig as type
    

    The second option might cause some runtime issues as I don't know how the unassigned properties are accessed or used.