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()
.
final
to TypeScript: github.com/Microsoft/TypeScript/issues/8306@readonly
decorator, which will useObject.freeze
on the object, but that's not the same thing (it disallows any modification to the class).Object.hasOwnProperty.call(target, "some-property")
to check if property comes from object itself and not from prototype chain. You can use the same trick and it won't even matter if subclass shadows this method or not.