typescript - TypeScript 在类中实现接口
问题描述
我是 TypeScript 的新手,谁能帮我找出在课堂上实现接口的最佳实践?因为当我尝试遵循 Docs ( Class Heritage ) 时,我遇到了这样的问题:
- 声明接口
interface Notification {
message: string;
send(msg?: string): void;
}
- 在类中实现接口
constructor()
class Notifier implements 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!");
不幸的是,我发现了如下错误消息:
“Notifier”类错误地实现了“Notification”接口。“通知程序”类型缺少“通知”类型的以下属性:操作、徽章、正文、数据等 19 个。
谁能告诉我我怎么了?提前致谢!
解决方案
您的问题是TypeScript 标准库已经包含一个全局范围的interface
名称Notification
,该名称与Web Workers API的Notification
接口相对应。因此,您的定义只是将其他成员合并到其中。这显然不是你想要的。Notification
interface
此处的修复方法是将您重命名为类似的interface
其他名称MyNotification
,或者创建一个module
或namespace
为您的代码创建一个新的命名范围:
// 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!");
哪个可以按需要工作。
推荐阅读
- python - 可视化傅立叶变换的计算有效方法?
- hyperledger-fabric - 有没有办法使用 Hyperledger Composer 设置多个对等点?
- r - 将栅格中的值替换为另一个栅格中的值
- python - Django:省选择字段依赖于州选择字段
- c# - 如何在 UWP 中设置 CommandBarFlyout 的主题?
- timestamp - 在 PowerBI (Desktop) 中,如何对每天(或每周或每月)的时间戳进行分组?
- c# - C# 中响应式数据轮询的有效设置
- visual-studio-code - 如何从 VSCode 中的降价文档链接到编辑器中的另一个文件
- java - 如何使用 mapstruct 或 modelmapper 从一个对象递归更新嵌套对象?
- javascript - 如何在javascript中的方法内传递动态变量?