Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在TypeScript中的所有子项中创建必填字段?_Javascript_Typescript - Fatal编程技术网

Javascript 如何在TypeScript中的所有子项中创建必填字段?

Javascript 如何在TypeScript中的所有子项中创建必填字段?,javascript,typescript,Javascript,Typescript,假设我有一个类Base,如何使继承自Base的所有子类独立实现某个字段 例如,Base具有必需的成员函数func(),a扩展Base和B扩展a。我想在A和B中都需要func()定义 我能这样做吗?怎么做?谢谢 要进行必要的定义,您必须使用接口: interface MyPerfectlyNamedInterface { func(): any; // no definition here, since interfaces are inherently abstract } class B

假设我有一个类
Base
,如何使继承自
Base
的所有子类独立实现某个字段

例如,
Base
具有必需的成员函数
func()
a
扩展
Base
B
扩展
a
。我想在
A
B
中都需要
func()
定义


我能这样做吗?怎么做?谢谢

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

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 class Base {
  abstract func(): any;
}

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

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

您可以像这样在基类中标记方法抽象

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

class A extends Base {
  func(): void {
    console.log("Doing something in A class");
  }
}

class B extends Base {
  func(): void {
    console.log("Doing something in B class");
  }
}



@DimaParzhitsky是的,完全正确。在您的评论之前已经了解到:)很抱歉删除,为什么要这样做?谢谢您,Dima,但casecade正是我想要的…我想,这目前不可能:(实际上我想要的是,当有人创建一个类
C
扩展我的
a
B
Base
,他就会知道他应该定义一个
func()
对于
C
。我想他自己可能不会添加
实现
语句。这只能通过平面继承结构(没有子级)实现,如果基类是
抽象的
。否则-请注意
类base{func():any{}
固有地实现了
MyPerfectlyNamedInterface
implements
关键字对于编写类很有用,但它不影响类型。谢谢Berk,但是类
B
应该扩展
A
而不是