【问题标题】:TypeScript implementing interface in classTypeScript 在类中实现接口
【发布时间】:2021-07-20 23:35:09
【问题描述】:

我是 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!");

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

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

谁能告诉我我的问题是什么?提前致谢!

【问题讨论】:

  • 旁白:我正在将您的message 属性从private 更改为public,否则您在解决当前错误后会遇到新错误。由于您不是在询问 privatepublic,因此这个问题超出了问题的范围,我们应该使用 public 来解决问题,就像我在下面的回答一样。
  • 是的,非常感谢您的解释

标签: typescript


【解决方案1】:

您的问题是the TypeScript standard library already includes a globally-scoped interface named Notification 对应于Web Workers API 中的Notification interface。因此,您的 Notification interface 定义就是 merging additional members into it。这显然不是你想要的。

这里的解决方法是将您的 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 link to code

【讨论】:

  • 非常感谢!我没有意识到,当我将该接口的名称更改为 MyNotification 时,它就可以工作了。
  • 但是,在实现接口的同时在构造函数中使用私有访问修饰符怎么样?由于在您的示例中,我们必须将 message 属性更改为 public。
  • 这是一个不同的问题,不是吗?如果我有一个MyNotification 对象,我应该被允许访问它的message 属性,根据您的接口定义。如果Notifier 使message 成为private 属性,那么我不能这样做。就像如果它应该是string,你就不能让它成为number。因此,将其设为private 会导致Notifier 不是有效的MyNotification。您可以在Notifier 中拥有私有属性,但它们不能与MyNotification 中的属性冲突。
  • 评论区不是讨论这个后续问题的好地方。你应该考虑做更多的研究来寻找像this one这样的现有问题,如果你找不到答案,考虑发布一个新问题。祝你好运!
猜你喜欢
  • 2019-06-27
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 2016-06-20
  • 1970-01-01
  • 2017-11-06
相关资源
最近更新 更多