我正在尝试创建一个抽象类,但事情并不像我希望的那样工作,而且我担心我的typescript知识是有限的,因为我认为这是一个相当通用的用例。
我有一个抽象的类程序。这个抽象类有一堆函数和属性。
abstract class Program {
someString: string = "bob";
someFunc(): void {
return;
}
someOtherfunc: void {
this.childFunc();
return;
}
}我还有一个接口'IProgram‘,看起来像这样
interface IProgram {
childFunc: () => void;
}class Child扩展了class Program,也实现了'IProgram‘接口
class Child extends Program implements IProgram {
childFunc(): void {
console.log("Hello World")
}
}因此,我不能让它工作,而不是得到某种破坏(IMHO)行为。
我已经尝试添加一个索引签名到‘程序’的工作,我没有得到TS错误,但然后一切工作在子程序。我不在乎在IProgram中丢失验证,因为这是不会改变的,但我不希望儿童程序能够去:
this.bob = 'potato'; //TS wont give an error because of index signature in parent我还尝试在抽象类中将'childFunc‘声明为类型any,但随后它抱怨说它应该是一个函数,而不是成员。我声明它的另一个问题是,我的实现'IProgram‘的子类将不再被强制实现'childFunc’,因为TS在头部中找到了它。
我还做了一个最小的stackBlitz重现这个问题
https://stackblitz.com/edit/typescript-po7hbo
我基本上只想让抽象类接受它的所有子类都将声明这些函数/属性。
发布于 2019-04-18 22:49:27
看起来您确实希望Program的所有具体子类都实现IProgram,因为您在Program的定义中引用了this.childFunc()。如果是这样,您应该声明Program实现IProgram,在Program中声明childFunc方法,并在Program中声明mark it as abstract
abstract class Program implements IProgram {
abstract childFunc(): void; // marked as abstract
someString: string = "bob";
someFunc(): void {
return;
};
someOtherfunc(): void {
this.childFunc(); // okay now
return;
};
}
// you can remove the "implements IProgram" from Child since the parent has it
class Child extends Program {
childFunc(): void {
console.log("Hello World")
}
}抽象方法是在它们的抽象类中声明的,但没有实现,所有具体的子类都必须实现它们,否则会出现错误:
class Oops extends Program { // error!
// ~~~~
// Non-abstract class 'Oops' does not implement inherited
// abstract member 'childFunc' from class 'Program'.
}希望这能有所帮助。祝好运!
https://stackoverflow.com/questions/55748232
复制相似问题