typescript - 在这种情况下如何在 Typescript 中实现继承
问题描述
我的问题是我希望 Product 类实现两个类 [Review 和 Category] 以在我的代码中获得更多的可伸缩性。然而,我陷入了困境。我什至尝试使用 Mixins,但我不得不重新分配 Category 和 Review 中的所有方法,有没有人知道这样做的更好和更智能的解决方案?
interface Fetch {
getInfo() :string;
}
class Review implements Fetch {
getInfo(): string {
return 'Nice Product'
}
getName(): string {
return 'Shirt Star wars'
}
geRate(): string {
return '5 stars'
}
}
class Category implements Fetch {
getInfo(): string {
return 'Nice Category'
}
getCategory(): string {
return 'Geek'
}
getSimilar(): string[] {
return []
}
}
class Product extends Review {
constructor() {
super();
}
}
let Shirt = new Product()
Shirt.getInfo()
Shirt.geRate()
解决方案
这是您所问的示例:
interface Fetch {
getInfo() :string;
}
interface ReviewInterface extends Fetch{
getName(): string;
getRate(): string;
}
interface CategoryInterface extends Fetch{
getCategory(): string;
getSimilar(): string[];
}
class Review implements ReviewInterface {
getInfo(): string {
return 'Nice Product'
}
getName(): string {
return 'Shirt Star wars'
}
geRate(): string {
return '5 stars'
}
}
class Category implements CategoryInterface {
getInfo(): string {
return 'Nice Category'
}
getCategory(): string {
return 'Geek'
}
getSimilar(): string[] {
return []
}
}
class Product implements ReviewInterface, CategoryInterface {
constructor() {
super();
}
// .... Here goes all implementations...
}
let Shirt = new Product()
Shirt.getInfo()
Shirt.geRate()
推荐阅读
- python - 如何在 python3.x 中通过 seaborn 正确绘制箱线图
- mysql - 如何通过比较表 a 和表 b 的记录来创建新表?
- android - 将 Google 服务凭据添加到 Android 应用以连接 Google Cloud
- python - 如何优化和查找大输入的输出?
- python - Python多线程执行 - 不可扩展
- php - 如何使用 PHP 对大型文本文件进行排序并搜索重复项?
- spring-boot - 如何正确处理 SOAP Web 服务引发的客户端异常
- c# - 实体框架通用方法不接受包含方法
- scala - 如何在不使用可变变量的情况下在 scala 中编写迭代器?
- java - Syncfusion PDF Viewer 中不显示上传的 PDF?