在 Nodejs 中实现具有多重继承的接口 class
Implement an interfaces with multiple inheritance in a Nodejs class
我尝试了下面的方法来创建接口并实现它。
class AInterface {
constructor () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
通过扩展在 class 中实现了它。 (注意我已经使用ts-mixer实现了多重继承
import AInterface from './AInterface'
import { Mixin } from 'ts-mixer'
class ClassA extends Mixin(AnotherClass, AInterface) {
constructor () {
super()
}
methodA () {
return 'test'
}
methodB () {
return 'test'
}
}
export default ClassA
这将引发错误 class should implement a methodA() method
。这意味着我在界面中所做的检查失败 if (!this.methodA)
。
当我删除 Mixin 并仅扩展接口时,这工作正常。 (class ClassA extends AInterface
)
是否有更好的方法或如何解决此问题?
节点版本 - 14
问题似乎是 AInterface
的构造函数没有获得正确的 this
。所以它没有看到 methodA
或 methodB
.
解决方法是避免在构造函数中进行该检查。
import AInterface from "./AInterface.mjs";
import { Mixin, settings } from "ts-mixer";
settings.initFunction = "init";
class ClassA extends Mixin(AnotherClass, AInterface) {}
AInterface.js
class AInterface {
init () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
注意上面init()
方法的使用。
我尝试了下面的方法来创建接口并实现它。
class AInterface {
constructor () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
通过扩展在 class 中实现了它。 (注意我已经使用ts-mixer实现了多重继承
import AInterface from './AInterface'
import { Mixin } from 'ts-mixer'
class ClassA extends Mixin(AnotherClass, AInterface) {
constructor () {
super()
}
methodA () {
return 'test'
}
methodB () {
return 'test'
}
}
export default ClassA
这将引发错误 class should implement a methodA() method
。这意味着我在界面中所做的检查失败 if (!this.methodA)
。
当我删除 Mixin 并仅扩展接口时,这工作正常。 (class ClassA extends AInterface
)
是否有更好的方法或如何解决此问题?
节点版本 - 14
问题似乎是 AInterface
的构造函数没有获得正确的 this
。所以它没有看到 methodA
或 methodB
.
解决方法是避免在构造函数中进行该检查。
import AInterface from "./AInterface.mjs";
import { Mixin, settings } from "ts-mixer";
settings.initFunction = "init";
class ClassA extends Mixin(AnotherClass, AInterface) {}
AInterface.js
class AInterface {
init () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
注意上面init()
方法的使用。