我有两个组件,一个是父组件,另一个是子组件。 child 从 parent 延伸。父级有一个方法 open()。 Child 通过重写并添加参数来重载 open()。它会导致错误:open() 是一个属性,并且属性类型在类之间不匹配。
open() => void
不等于
open(message: string) => void
父级:
export class ParentClass {
constructor() { super(); }
open(){
return "Hello World!";
}
}
child :
export class ChildClass extends ParentClass {
constructor() { super(); }
open(message: string){
return message;
}
}
最佳答案
这段代码不起作用的原因很简单:
let parent: ParentClass = new ParentClass();
parent.open();
parent = new ChildClass();
// what happens now?
parent.open();
在第三行代码之后,parent
仍然是ParentClass
的类型,因此open
调用应该是有效的。另一方面,它包含一个 ChildClass
,因此我们没有为此方法提供必要的参数:message: string
。这是一个悖论。
如果您希望此代码有效,两个方法应共享相同的参数。
给您的两个提示:
- 避免继承。说真的,很可能你不需要它,而且很可能它只会导致问题,即使一开始看起来并不如此。尝试:composition over inheritance 。
- 如果您仍想遵循这种方式,请尝试this answer .
关于angular - Angular2 中的方法重写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38230946/