MST

星途 面试题库

面试题:TypeScript多态在实际前端开发场景中的应用

请描述一个实际的前端开发场景(比如页面组件渲染),说明如何利用TypeScript的多态特性来优化代码结构和提高可维护性,同时给出关键的代码片段及相应解释。
15.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

场景描述

在一个电商产品列表页面中,需要渲染不同类型的产品卡片组件,如普通商品卡片、促销商品卡片和新品卡片。这些卡片有一些共同的属性和方法,但也有各自独特的部分。

利用TypeScript多态特性优化

  1. 定义基类
// 定义产品卡片基类
class ProductCard {
    constructor(public title: string, public price: number) {}
    // 基类方法,用于显示基本信息
    displayBasicInfo(): void {
        console.log(`Title: ${this.title}, Price: ${this.price}`);
    }
}

这里定义了一个ProductCard基类,包含titleprice属性,以及一个显示基本信息的方法displayBasicInfo。这是所有产品卡片的共性部分。

  1. 定义子类
// 普通商品卡片子类
class NormalProductCard extends ProductCard {
    constructor(title: string, price: number) {
        super(title, price);
    }
    // 可以重写基类方法或添加新方法
    displayFullInfo(): void {
        super.displayBasicInfo();
        console.log('This is a normal product.');
    }
}

// 促销商品卡片子类
class PromotionProductCard extends ProductCard {
    constructor(title: string, price: number, public discount: number) {
        super(title, price);
    }
    // 重写显示基本信息方法以包含折扣信息
    displayBasicInfo(): void {
        console.log(`Title: ${this.title}, Price: ${this.price}, Discount: ${this.discount}%`);
    }
}

// 新品卡片子类
class NewProductCard extends ProductCard {
    constructor(title: string, price: number) {
        super(title, price);
    }
    // 新方法表示新品特性
    showNewMark(): void {
        console.log('This is a new product!');
    }
}

每个子类继承自ProductCard基类,既拥有基类的属性和方法,又可以根据自身特点重写方法或添加新方法。例如PromotionProductCard重写了displayBasicInfo方法以显示折扣信息。

  1. 多态使用
// 定义一个函数来展示产品卡片信息
function displayProductCard(card: ProductCard) {
    card.displayBasicInfo();
    if (card instanceof NormalProductCard) {
        card.displayFullInfo();
    } else if (card instanceof PromotionProductCard) {
        // 可以处理促销商品特有的逻辑
    } else if (card instanceof NewProductCard) {
        (card as NewProductCard).showNewMark();
    }
}

// 创建不同类型的产品卡片实例
const normalCard = new NormalProductCard('Normal Product', 100);
const promotionCard = new PromotionProductCard('Promotion Product', 200, 10);
const newCard = new NewProductCard('New Product', 150);

// 调用函数展示卡片信息
displayProductCard(normalCard);
displayProductCard(promotionCard);
displayProductCard(newCard);

displayProductCard函数接受一个ProductCard类型的参数,由于多态特性,它可以处理任何子类的实例。根据实际传入的子类实例,函数可以执行相应的方法,这样在渲染产品卡片组件时,代码结构更加清晰,可维护性更高。当需要添加新的产品卡片类型时,只需要定义新的子类并遵循基类的接口,而不需要大幅修改现有的展示逻辑。