Is there an equivalent to "sealed" or "final" in TypeScript?

I am trying to implement a method in a superclass that should be available for use, but not modified, in subclasses. 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 was that any subclass of BaseClass could not only omit the implementation of universalBehavior() , but not even be able to provide an implementation. Isn't that still possible in TypeScript? Intellisense complains when I omit the implementation in my subclasses. The best I can do is the following:

 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 subclass ever implements universalBehavior() with anything other than calling super.universalBehavior() .

+12
source share
2 answers

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

See:

+11
source

An example implementation of hacking a "private method" as a readonly property of a type function that throws a compiler error when trying to override in an 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 using a private constructor:

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

Source: https://habr.com/ru/post/1265496/


All Articles