强制子类在重写方法上调用 super

2024-04-29

当扩展类时,有时我们会忘记在已经实现的方法中调用超类实现。

当方法被重写而不调用 super 时,有什么方法可以通过抛出错误或其他内容来防止这种情况发生?


Example

class MainClass implements OnInit
{
    ngOnInit() {
        // base implementation
    }
}

class InnerClass extends MainClass
{
    ngOnInit() {
        super.ngOnInit(); // ---> throw error if didn't call this line
        // additional implementation
    }    
}

关于它有一个有趣的讨论github https://github.com/microsoft/TypeScript/issues/21388, 这个单词concrete被提议了,但是没有,目前 TS 不支持它。您必须为此使用一些解决方法(也在该页面上列出)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

强制子类在重写方法上调用 super 的相关文章

随机推荐