本文介绍了是否有等同于“密封"的标签?或“最终"在TypeScript中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在一个超类中实现一个方法,该方法应该可以在子类中使用,但不能更改.考虑一下:

I'm trying to implement a method in a super class that should be available for use, but not changeable, in sub classes. Consider this:

export abstract class BaseClass {
    universalBehavior(): void {
        doStuff(); // Do some universal stuff the same way in all sub classes
        specializedBehavior(); // Delegate specialized stuff to sub classes
    }

    protected abstract specializedBehavior(): void;
}

我的意图是,BaseClass的任何子类不仅可以自由省略universalBehavior()的实现,而且甚至不被允许提供实现.在TypeScript中还不可能吗?当我在子类中省略实现时,Intellisense会抱怨.我似乎能做的最好的事情是:

My intention would be that any sub class of BaseClass would not only be free to omit implementation of universalBehavior(), but not even be allowed to provide an implementation. Is this not (yet) possible in TypeScript? Intellisense complains when I omit the implementation in my sub classes. The best I can seem to do is this:

export class SubClass extends BaseClass {
    universalBehavior(): void {
        super.universalBehavior();
    }

    specializedBehavior(): void {
        // sub class' implementation
    }
}

显然这是有问题的,因为我必须确保没有子类可以实现除调用super.universalBehavior()之外的任何其他方法来实现universalBehavior().

Obviously this is problematic because I have to ensure that no sub class ever implements universalBehavior() with anything other than a call to super.universalBehavior().

推荐答案

否,在撰写本文时还没有.对于这种关键字,有一个建议正在考虑中,但可能会实施,甚至可能永远不会实施.

No, at the time of this writing there is not. There is a proposal for such a keyword which is still being considered, but may or may not ever be implemented.

请参阅:

  • github.com/Microsoft/TypeScript/issues/9264, and
  • github.com/Microsoft/TypeScript/issues/8306

这篇关于是否有等同于“密封"的标签?或“最终"在TypeScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:14