MST

星途 面试题库

面试题:TypeScript接口与抽象类的多态性实现对比

在TypeScript中,如何通过接口和抽象类分别实现多态性?详细描述其实现方式,包括类型定义、方法重写等关键环节,并分析两者在实现多态时的优势与局限性,给出相应代码示例。
15.9万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

通过接口实现多态性

  1. 类型定义:接口用于定义对象的形状,它只定义方法签名,不包含方法的具体实现。
// 定义一个接口
interface Animal {
    speak(): string;
}

// 定义实现该接口的类
class Dog implements Animal {
    speak(): string {
        return 'Woof!';
    }
}

class Cat implements Animal {
    speak(): string {
        return 'Meow!';
    }
}
  1. 使用多态:可以通过将不同类的实例赋值给接口类型的变量来实现多态。
function makeSound(animal: Animal) {
    console.log(animal.speak());
}

const dog = new Dog();
const cat = new Cat();

makeSound(dog); 
makeSound(cat); 
  1. 优势
    • 接口更灵活,一个类可以实现多个接口,从而实现多种不同类型的多态行为。
    • 接口常用于定义对象之间的契约,适合在不同模块或团队之间进行协作开发。
  2. 局限性
    • 接口不能包含属性的初始值,也不能有具体的方法实现,所以复用性较差。

通过抽象类实现多态性

  1. 类型定义:抽象类可以包含抽象方法和具体方法,抽象方法只有声明,没有实现,必须在子类中被重写。
// 定义一个抽象类
abstract class Shape {
    // 抽象方法
    abstract area(): number;
    // 具体方法
    printInfo() {
        console.log('This is a shape.');
    }
}

// 定义继承自抽象类的子类
class Circle extends Shape {
    constructor(private radius: number) {
        super();
    }
    area(): number {
        return Math.PI * this.radius * this.radius;
    }
}

class Rectangle extends Shape {
    constructor(private width: number, private height: number) {
        super();
    }
    area(): number {
        return this.width * this.height;
    }
}
  1. 使用多态:通过将子类实例赋值给抽象类类型的变量来体现多态。
function calculateArea(shape: Shape) {
    console.log(shape.area());
}

const circle = new Circle(5);
const rectangle = new Rectangle(4, 5);

calculateArea(circle); 
calculateArea(rectangle); 
  1. 优势
    • 抽象类可以包含具体方法和属性,提高了代码的复用性。
    • 抽象类能更好地体现类之间的继承关系,适合用于创建一个通用的基类。
  2. 局限性
    • 一个类只能继承一个抽象类,限制了类的多重继承能力。