简体   繁体   English

在 typescript 中的基础 class 的子类中实现的调用方法

[英]call method to be implemented in subclass from base class in typescript

//BaseClass.ts

class Base {
  connstructor() {}

  callSubClassMethod = () => {
    return this.subMethod();
  }

}


//SubClass.ts

class Sub extends Base {
  constructor() {
    super();
  }

  subMethod = () => {
    console.log('Iam subclass method')
  }
}

Is this possible in typescript?这在 typescript 中是否可行? the base class complains that subMethod is not defined.基础 class 抱怨subMethod未定义。 This works without the class encapsulation, I have been looking for a way around this as majority of my codebase is in ES6+ syntax这在没有 class 封装的情况下工作,我一直在寻找解决这个问题的方法,因为我的大部分代码库都是 ES6+ 语法

If your Base class implementation relies on a method that is not (and cannot be) defined, then Base is abstract and should be declared as such:如果您的Base class 实现依赖于未(也不能)定义的方法,则Baseabstract的,应该这样声明:

abstract class Base {

  abstract subMethod(): any;

  callSubClassMethod = () => {
    return this.subMethod();
  }

} 

If the method can be defined, so that it performs some default action or returns some default value, then simply define it in Base :如果可以定义该方法,以便它执行一些默认操作或返回一些默认值,那么只需在Base中定义它:

class Base {

  subMethod() {
      // do some default thing, for example, nothing
  }

  callSubClassMethod = () => {
    return this.subMethod();
  }

} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM