javascript - 如何在 TypeScript 中创建所有子项都需要的字段?
问题描述
假设我有一个 class Base
,我如何让所有继承自Base
实现的孩子自己实现某个字段?
例如,有Base
一个必需的成员函数extends和extends 。我想在和中都需要定义。func()
A
Base
B
A
func()
A
B
我可以这样做吗?怎么做?谢谢!
解决方案
要进行定义,您必须使用接口:
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 */ }
}
推荐阅读
- c# - 将所有整数类型从 repo 获取到现有对象的列表中
- oracle - 在 Oracle APEX 的徽章列表中选择“空”值的方法
- c++ - 使用迭代器插入时的段错误
- sql - 从一个 SELECT 查询到第二个 SELECT 查询的 SQL SERVER JOIN ID 行
- c - 是否需要在 C 中的每次调用时重置信号处理程序?
- python-3.x - Pandas 与内部连接合并返回 KeyError
- c++ - 无法在 Mac OS X 上的 Visual Code 中调试 C++
- python - 带有点符号的 Pandas 列在应用期间引用索引
- javascript - 执行单击(出现检查)操作,再次执行第二次单击(检查消失)操作。需要,第二次点击删除第一个动作
- ios - 嵌入视频 Swift