简体   繁体   English

实现接口时出现TypeScript错误

[英]TypeScript Error On Implementing Interface

Compiler Error- 编译器错误-

Class 'MessageBus' incorrectly implements interface 'IMessageBus'. 类“ MessageBus”错误地实现了接口“ IMessageBus”。 Property 'dispatch' is missing in type 'MessageBus'. 类型“ MessageBus”中缺少属性“ dispatch”。

IMessageBus Interface- IMessageBus接口-

export interface IMessageBus {
  dispatch: (eventName: string, info?: any) => void;
  listen: (eventName: string, callback: Function) => void;
}

MessageBus Class- MessageBus类

import {IMessageBus} from './IMessageBus';

export class MessageBus implements IMessageBus {
  static listeners: Object[] = [];
  public static dispatch(event: string, info?: any): void {
     this.listeners
        .forEach((l) => {
           if (l["event"] === event) {
               l["cb"](info);
           }
        });
  }

  public static listen(event:string, cb: (any) => any):void {
    this.listeners.push({event: event, cb: cb});
  }
}

Please advice on how to resolve this. 请提供有关如何解决此问题的建议。

Thierry's answer is correct. 蒂埃里的回答是正确的。

Your interface is not defined wrong. 您的界面定义不正确。 But a more idiomatic definition would look like: 但更惯用的定义如下所示:

export interface IMessageBus {
  dispatch(eventName: string, info?: any): void;
  listen(eventName: string, callback: Function): void;
} 

I think that you should remove the static keyword for your methods in the class implementing the interface: 我认为您应该在实现接口的类中为方法删除static关键字:

export class MessageBus implements IMessageBus {
  listeners: Object[] = [];
  public dispatch(event: string, info?: any): void {
    this.listeners
      .forEach((l) => {
        if (l["event"] === event) {
           l["cb"](info);
        }
      });
  }

  public listen(event:string, cb: (any) => any):void {
    this.listeners.push({event: event, cb: cb});
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM