什么是typescript多态

0 阅读1分钟

在 TypeScript 中,多态(Polymorphism)是指同一个接口或基类可以有多种形式。多态允许你使用一个统一的接口来表示不同类型的对象,并且可以在运行时决定调用哪个具体的方法。多态是面向对象编程(OOP)中的一个核心概念,它有助于提高代码的灵活性和可扩展性。 TypeScript 支持多态主要通过以下几种方式实现:

  1. 接口多态: 通过定义一个接口,多个类可以实现这个接口,从而表现出多态性。
interface Animal {
    makeSound(): void;
}

class Dog implements Animal {
    makeSound() {
        console.log("Woof!");
    }
}

class Cat implements Animal {
    makeSound() {
        console.log("Meow!");
    }
}

function animalSound(animal: Animal) {
    animal.makeSound();
}

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

animalSound(dog); // 输出: Woof!
animalSound(cat); // 输出: Meow!
  1. 类继承多态: 通过继承基类,子类可以重写基类的方法,从而表现出多态性。
class Animal {
   makeSound() {
       console.log("Some generic animal sound");
   }
}

class Dog extends Animal {
   makeSound() {
       console.log("Woof!");
   }
}

class Cat extends Animal {
   makeSound() {
       console.log("Meow!");
   }
}

function animalSound(animal: Animal) {
   animal.makeSound();
}

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

animalSound(dog); // 输出: Woof!
animalSound(cat); // 输出: Meow!
  1. 泛型多态: 通过使用泛型,函数或类可以处理多种类型的数据,从而表现出多态性。
function printLength<T extends { length: number }>(arg: T): void {
   console.log(arg.length);
}

printLength("Hello"); // 输出: 5
printLength([1, 2, 3]); // 输出: 3

多态性使得代码更加模块化和易于维护,因为它允许你在不改变现有代码的情况下添加新的功能或行为。