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

后端 未结 3 456
慢半拍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:15

    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:

    • github.com/Microsoft/TypeScript/issues/9264, and
    • github.com/Microsoft/TypeScript/issues/8306
    0 讨论(0)
  • 2021-01-07 17:15
    // I use this workaround:
    
    export default class CreateHandler extends BaseHandler {
        // final prop used as method
        public readonly create = (blueprint: Blueprint): Response<Record> => {
            return blueprint.create();
        };
    
        // normal method
        public store(blueprint: Blueprint): Response<Record> {
            return this.response(blueprint.create());
        }
    }
    
    0 讨论(0)
  • 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<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 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)
    
    0 讨论(0)
提交回复
热议问题