在 typescript 中从 base class 调用要在 subclass 中实现的方法
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')
}
}
这在打字稿中可行吗?
base class 抱怨 subMethod 没有定义。
这在没有 class 封装的情况下工作,我一直在寻找解决这个问题的方法,因为我的大部分代码库都是 ES6+ 语法
如果您的 Base
class 实现依赖于未(且不能)定义的方法,则 Base
是 abstract
并且应该这样声明:
abstract class Base {
abstract subMethod(): any;
callSubClassMethod = () => {
return this.subMethod();
}
}
如果方法 可以 被定义,以便它执行一些默认操作或 returns 一些默认值,那么只需在 Base
中定义它:
class Base {
subMethod() {
// do some default thing, for example, nothing
}
callSubClassMethod = () => {
return this.subMethod();
}
}
//BaseClass.ts
class Base {
connstructor() {}
callSubClassMethod = () => {
return this.subMethod();
}
}
//SubClass.ts
class Sub extends Base {
constructor() {
super();
}
subMethod = () => {
console.log('Iam subclass method')
}
}
这在打字稿中可行吗? base class 抱怨 subMethod 没有定义。 这在没有 class 封装的情况下工作,我一直在寻找解决这个问题的方法,因为我的大部分代码库都是 ES6+ 语法
如果您的 Base
class 实现依赖于未(且不能)定义的方法,则 Base
是 abstract
并且应该这样声明:
abstract class Base {
abstract subMethod(): any;
callSubClassMethod = () => {
return this.subMethod();
}
}
如果方法 可以 被定义,以便它执行一些默认操作或 returns 一些默认值,那么只需在 Base
中定义它:
class Base {
subMethod() {
// do some default thing, for example, nothing
}
callSubClassMethod = () => {
return this.subMethod();
}
}