Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

inheritance - Is there an equivalent to "sealed" or "final" in 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;
}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...