【问题标题】:How can I do that if childclass do not call the fatherclass's override funtion, there will throw Error with TypeScript如果子类不调用父类的覆盖函数,我该怎么做,TypeScript 会抛出错误
【发布时间】:2021-11-21 21:20:27
【问题描述】:

** 问题:如果孩子不调用父亲的 override 函数,TypeScript 会抛出 Error 怎么办?**

class aaa {
  create() { }
}

class bb extends aaa {
  create() {
    // if not call the father's funtion, there will throw Error.
    // super.create()
  }
}

【问题讨论】:

  • 就像Android中的@Callsuper

标签: typescript extends


【解决方案1】:

an open issue for this on the TypeScript repo 所以看来你不能直接做你想做的事。

在那个问题上有一些有趣的讨论,包括这样的解决方法:

type callSuper = never;

class aaa {
  create(): callSuper { 
      return undefined as callSuper;
  }
}

class bb extends aaa {
  create() {
    // if not calling and returning the father's funtion, will throw Error.
    // return super.create()
  }
}

还提到for Martin Fowler,试图从父类强制或期望子类系统地调用函数是一种反模式。

他建议像这样使用Template Method pattern

class aaa {
    calledInTheParent(){
        this.create();
        // what needs to be always done here
    }

    protected create(){
        // this is just an empty hook to be overridden by children,
        // to let them do additional things 
    }
}

class bb extends aaa {
    protected create(){
        // do what you need in the child here without worrying 
        // about calling a parent function
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多