首页 > 解决方案 > TypeScript 在类中实现接口

问题描述

我是 TypeScript 的新手,谁能帮我找出在课堂上实现接口的最佳实践?因为当我尝试遵循 Docs ( Class Heritage ) 时,我遇到了这样的问题:

  1. 声明接口
interface Notification {
    message: string;
    send(msg?: string): void;
}
  1. 在类中实现接口constructor()
class Notifier implements Notification {
    constructor(
        public message: string,
    ){}

    send(customMsg?: string): void {
        if (customMsg) {
            console.log(customMsg);
        } else {
            console.log(this.message);
        }
    }
}
  1. 例如,使用类
const hello = new Notifier("hello");
hello.send();
hello.send("Alert!");

不幸的是,我发现了如下错误消息:

“Notifier”类错误地实现了“Notification”接口。“通知程序”类型缺少“通知”类型的以下属性:操作、徽章、正文、数据等 19 个。

谁能告诉我我怎么了?提前致谢!

标签: typescript

解决方案


您的问题是TypeScript 标准库已经包含一个全局范围的interface名称Notification,该名称与Web Workers API的Notification接口相对应。因此,您的定义只是将其他成员合并到其中。这显然不是你想要的。Notification interface

此处的修复方法是将您重命名为类似的interface其他名称MyNotification,或者创建一个modulenamespace为您的代码创建一个新的命名范围:

// use of "export" makes your code a module
export interface Notification { 
    message: string;
    send(msg?: string): void;
}

或者

namespace MyNamespace {
  export interface Notification {
    message: string;
    send(msg?: string): void;
  }
}

然后您应该可以稍后参考它。如果你使用这种namespace方法,你会得到这个:

class Notifier implements MyNamespace.Notification {
  constructor(
    public message: string, 
  ) { }

  send(customMsg?: string): void {
    if (customMsg) {
      console.log(customMsg);
    } else {
      console.log(this.message);
    }
  }
}


const hello = new Notifier("hello");
hello.send();
hello.send("Alert!");

哪个可以按需要工作。

Playground 代码链接


推荐阅读