首页 > 解决方案 > 在这种情况下如何在 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()

标签: typescriptoopdesign-patternsscalability

解决方案


这是您所问的示例:

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()

推荐阅读