首页 > 解决方案 > 如何在 TypeScript 中创建所有子项都需要的字段?

问题描述

假设我有一个 class Base,我如何让所有继承自Base实现的孩子自己实现某个字段?

例如,有Base一个必需的成员函数extends和extends 。我想在和中都需要定义func()ABaseBAfunc() AB

我可以这样做吗?怎么做?谢谢!

标签: javascripttypescript

解决方案


要进行定义,您必须使用接口:

interface MyPerfectlyNamedInterface {
  func(): any; // no definition here, since interfaces are inherently abstract
}

class Base implements MyPerfectlyNamedInterface {
  func(): any { /* definition is required */ }
}

// note that A does _not_ extend Base
class A implements MyPerfectlyNamedInterface {
  func(): any { /* definition is required */ }
}

class B implements MyPerfectlyNamedInterface {
  func(): any { /* definition is required */ }
}

但是,如果子类扩展了对您的函数具有定义的基类(例如,如果A将扩展Base和/或B将扩展A),则再次不需要定义:

interface MyPerfectlyNamedInterface {
  func(): any;
}

class Base implements MyPerfectlyNamedInterface {
  func(): any { /* definition is required */ }
}

// note that A _does_ extend Base
class A extend Base implements MyPerfectlyNamedInterface {
  func(): any { /* definition is not required */ }
}

class B extend A implements MyPerfectlyNamedInterface {
  func(): any { /* definition is not required */ }
}

所以,我想,这对于你的设置来说是不可能的。


此外,您可以使用类实现这一点abstract,但同样,它不会“级联”到您想要的子类:

abstract class Base {
  abstract func(): any;
}

class A extends Base {
  func(): any { /* definition is required */ }
}

class B extends A {
  func(): any { /* definition is not required */ }
}

推荐阅读