Is there an equivalent to “sealed” or “final” in T

2019-06-15 16:09发布

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

2条回答
疯言疯语
2楼-- · 2019-06-15 16:43

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:

查看更多
时光不老,我们不散
3楼-- · 2019-06-15 16:54

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'"
}
查看更多
登录 后发表回答