在TypeScript中,如何防止在派生类上调用方法?

Ven*_*ryx 2 class subclass derived-class typescript

有三个班级.

// in external library, which I don't want to modify
class ComponentBase {
    // I want calling this to be disallowed
    forceUpdate() {}
}

class ComponentBase_MyVersion extends ComponentBase {
    // I want subclasses to always call this, instead of forceUpdate()
    Update() {}
}

class MyComponent extends ComponentBase_MyVersion {
    DoSomething() {
        // I want this to be disallowed
        this.forceUpdate();

        // forcing the subclass to call this instead
        this.Update();
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点,只改变ComponentBase_MyVersion

有没有办法"隐藏"基层成员?

或者也许是一种覆盖定义的方法 - 比如C#中的"new"关键字 - 让我破坏方法定义,至少在尝试调用它时会出现警告?

Diu*_*lei 5

OOP不允许您进行此类方法取消.您可以使用您建议的Exception在您的类上实现此功能,或使用组合:https://en.wikipedia.org/wiki/Composition_over_inheritance

例1:

class ComponentBase {
    forceUpdate() {}
}

class ComponentBase_MyVersion extends ComponentBase {
    Update() {}
    forceUpdate() {
        throw new Error("Do not call this. Call Update() instead.");
    }
}

class MyComponent extends ComponentBase_MyVersion {
    DoSomething() {
        // wil raise an exception
        this.forceUpdate();
        this.Update();
    }
}
Run Code Online (Sandbox Code Playgroud)

实施例2(组合物):

class ComponentBase {
    forceUpdate() {}
}

class ComponentBase_MyVersion {
    private _component: ComponentBase = ...;
    Update() {}
    // expose _component desired members ...
}

class MyComponent extends ComponentBase_MyVersion {
    DoSomething() {
        // compilation error
        this.forceUpdate();
        this.Update();
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望我帮忙.