oop - typescript 抽象方法重载

标签 oop typescript abstract

我想像这样在抽象类中重载抽象方法:

abstract class Animal {

    public abstract communicate(sentence: string): void;
    public abstract communicate(notes: string[]): void;

}

class Human extends Animal {

    public communicate(sentence: string): void {
        // Do stuff
    }

}

class Bird extends Animal {

    public communicate(notes: string[]): void {
        // Do stuff
    }

}

但是,Typescript 报错,指出我错误地扩展了基类 (Animal)

我做错了什么吗?就像期望根据 OOP 无论如何都会起作用的东西一样?还是 Typescript 不支持?

注意:与本例不同,参数的类型可以是完全不同的类型。

最佳答案

就像@DavidSherret 所说的,子类必须实现所有抽象类重载,而不仅仅是其中一个。因此,使用抽象类重载,您将无法真正做到您想做的事。

因为你想要的是让 BirdHuman 有不同的 communicate() 参数类型,由编译器强制执行,我会使用具有类型约束的泛型类型参数:

abstract class Animal<C extends string | string[]> {
    public abstract communicate(communication: C): void;
}

class Human extends Animal<string> {
    public communicate(sentence: string): void { }
}

class Bird extends Animal<string[]> {
    public communicate(notes: string[]): void { }
}

class Bynar extends Animal<boolean> { // Error: 'boolean' does not satisfy the constraint 'string | string[]'.
    public communicate(bit: boolean): void { }
}

const human = new Human();
human.communicate("hello"); // OK
human.communicate(["hello"]); // Error

const bird = new Bird();
bird.communicate("hello"); // Error
bird.communicate(["hello"]); // OK

提示:您可以使用 TS 2.3 default type arguments这里也是。

关于oop - typescript 抽象方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43981176/

相关文章:

PHP:变量中的类属性链接

PHP OOP - 尝试调用方法

angular - 如何从 Angular 为 6 的数组中删除重复的对象

typescript TS6053 : File ' .ts' not found

java - Number 类中的抽象方法

java - 具有所有抽象方法的抽象类 - 实际示例

java - 游戏的OO设计: moving player between rooms

Java 菜鸟需要澄清奇怪的重载方法问题

javascript - 移动焦点() - Angular 5

java - 从扩展类(class)调用