【问题标题】:Void is not assignable to > parameter of type '() => void'void 不可分配给 > '() => void' 类型的参数
【发布时间】:2021-05-03 22:40:15
【问题描述】:

我有一个 Angular 应用程序,它最初是用 Angular 2 编写的,然后升级到 7 和 9,现在尝试从 11 开始。

我的代码有一个函数,它在最初加载应用程序时通过套接字从后端获取用户的通知计数(下面的代码),它工作正常,但在 Angular 11 中不再这样做。我得到的错误是

'(notifyCount: INotifyCount) => void' 类型的参数不是 可分配给 '() => void'.ts(2345) 类型的参数 '(notifyMessage: INotification) => void' 不可分配给 '() 类型的参数 => void'.ts(2345)

所以我希望有人能告诉我如何解决这个问题,这样我就可以再次编译而不会出错。

socketInit() {
    this.socketService.ioInject('notifyCount', (notifyCount: INotifyCount) => {
        console.log('notifications count data ', notifyCount);
        this.notificationsCount = notifyCount.count;
    });
    this.socketService.ioInject('notifyMessage', (notifyMessage: INotification) => {
        console.log('notify message data ', notifyMessage);
        this.toasterService.pop('info', notifyMessage.subject, notifyMessage.message);
    });
}

我的套接字服务看起来像这样..

  ioInject(event: string, handler: () => void) {
    if (this.client) {
      this.client.on(event, handler);
    } else {
      console.warn('Socket client not initialized');
    }
  }

这是我的两门课..

export interface INotification {
  DocId: string;
  user_guid: string;
  type: string;
  status: string;
  subject: string;
  message: string;
  link: string;
  created_on: string;
}

export  interface INotifyCount {
  count: number;
}

【问题讨论】:

  • 这很简单,它说您的通知计数回调需要一个参数,其中您的ioInject 处理程序参数只是一个简单的非参数采用函数所以当它们不匹配时,它会给你这个bla bla is not assignable with bla bla。因此,要么将您的处理程序类型更改为任何或与您的函数匹配的模式:)

标签: angular typescript socket.io


【解决方案1】:

你必须改变ioInject方法的签名

ioInject(event: string, handler: (n: any) => void) {
    if (this.client) {
      this.client.on(event, handler);
    } else {
      console.warn('Socket client not initialized');
    }
  }

【讨论】:

  • 这违反了开放/封闭原则。根据代码示例,我猜这是一个通用服务,其中对象的类型可以是任何东西,但基于传入的事件类型。使用泛型甚至any 可能更安全参数类型。
猜你喜欢
  • 2021-04-18
  • 2017-09-21
  • 2021-08-24
  • 1970-01-01
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多