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

后端 未结 3 457
慢半拍i
慢半拍i 2021-01-07 16:38

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 clas         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 17:33

    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;
        constructor(element: JQuery) {
            this.element = element;
        }
        readonly public dispose = (): void => {
            this.element.remove();
        }
    }
    
    class MyClass extends BaseClass {
        constructor(element: JQuery) {
            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)
    

提交回复
热议问题