MST

星途 面试题库

面试题:TypeScript泛型类在复杂业务逻辑封装中的应用

在一个电商应用中,有不同类型的商品(如电子产品、服装等),每个商品都有不同的属性和行为。现在要求你使用TypeScript泛型类来封装一个通用的商品管理模块,该模块能够处理不同类型商品的添加、删除、查询操作,并且要考虑到不同商品类型之间的继承关系和类型兼容性。请阐述你的设计思路并编写相应代码示例。
17.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 定义商品基类:创建一个基础的商品类 BaseProduct,包含所有商品可能共有的属性和方法。
  2. 定义泛型类:使用泛型类 ProductManager<T> 来处理不同类型的商品,其中 T 是继承自 BaseProduct 的具体商品类型。
  3. 实现操作方法:在泛型类中实现添加、删除、查询商品的方法,这些方法要能够处理不同类型的商品实例。

代码示例

// 商品基类
class BaseProduct {
    id: number;
    name: string;

    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }
}

// 电子产品类,继承自BaseProduct
class ElectronicProduct extends BaseProduct {
    brand: string;

    constructor(id: number, name: string, brand: string) {
        super(id, name);
        this.brand = brand;
    }
}

// 服装类,继承自BaseProduct
class ClothingProduct extends BaseProduct {
    size: string;

    constructor(id: number, name: string, size: string) {
        super(id, name);
        this.size = size;
    }
}

// 商品管理泛型类
class ProductManager<T extends BaseProduct> {
    private products: T[] = [];

    // 添加商品方法
    addProduct(product: T): void {
        this.products.push(product);
    }

    // 删除商品方法
    removeProduct(id: number): void {
        this.products = this.products.filter(product => product.id!== id);
    }

    // 查询商品方法
    findProduct(id: number): T | undefined {
        return this.products.find(product => product.id === id);
    }
}

// 使用示例
// 创建电子产品管理实例
const electronicManager = new ProductManager<ElectronicProduct>();
const electronicProduct = new ElectronicProduct(1, '手机', 'Apple');
electronicManager.addProduct(electronicProduct);

// 创建服装管理实例
const clothingManager = new ProductManager<ClothingProduct>();
const clothingProduct = new ClothingProduct(2, 'T恤', 'M');
clothingManager.addProduct(clothingProduct);