我想像这样在抽象类中重载抽象方法:
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 所说的,子类必须实现所有抽象类重载,而不仅仅是其中一个。因此,使用抽象类重载,您将无法真正做到您想做的事。
因为你想要的是让 Bird
和 Human
有不同的 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/