Is there an equivalent to “sealed” or “final” in TypeScript?

心已入冬 提交于 2019-12-10 12:40:12

问题


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;
}

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
    }
}

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().


回答1:


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.

See:

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



回答2:


Example of implementation hack of 'sealed method' as readonly property of type function which throws compiler error when attempting to override in extended class:

abstract class BaseClass {
    protected element: JQuery<HTMLElement>;
    constructor(element: JQuery<HTMLElement>) {
        this.element = element;
    }
    readonly public dispose = (): void => {
        this.element.remove();
    }
}

class MyClass extends BaseClass {
    constructor(element: JQuery<HTMLElement>) {
        super(element);
    }
    public dispose(): void { } // Compiler error: "Property 'dispose' in type 'MyClass' is not assignable to the same property in base type 'BaseClass'"
}

TypeScript 2.0 supports "final" classes through using of private constructor:

class A {
    private constructor(){}
}

class B extends A{} //Cannot extend a class 'A'. Class constructor is marked as private.ts(2675)


来源:https://stackoverflow.com/questions/42814649/is-there-an-equivalent-to-sealed-or-final-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!