所以,我只是想知道是否可以编写这样的类。
// Declaration: flyingDog.ts
class Barkable {
bark = () => {
console.log('woof woof');
}
}
class Flyable {
fly = () => {
console.log('*soaring high*');
}
}
class FlyingDog {
transform = () => {
console.log('*initiate wings*');
}
}
export default Barkable(Flyable(FlyingDog)));
// Usage: index.ts
import FlyingDog from './flyingDog';
const awesomeness = new FlyingDog();
awesomeness.bark(); // 'woof woof'
awesomeness.fly(); // *soaring high*
awesomeness.transform(); // *initiate wings*
或者也许是这样(类似于React中的HoC):
// Declaration: flyingDog.ts
const withBarkable = (object:??) => {
return {
...object,
bark = () => {
console.log('woof woof');
}
}
}
const withBarkable = (object:??) => {
return {
...object,
fly = () => {
console.log('*soaring high*');
}
}
}
class FlyingDog {
transform = () => {
console.log('*initiate wings*');
}
}
export default withBarkable(withFlyable(FlyingDog)));
// Usage: index.ts
import FlyingDog from './flyingDog';
const awesomeness = new FlyingDog();
awesomeness.bark(); // 'woof woof'
awesomeness.fly(); // *soaring high*
awesomeness.transform(); // *initiate wings*
如何在不破坏tslint的情况下仍然获得类型安全性呢?
而且,我应该在object
和withBarkable()
参数中输入withFlyable()
的类型吗?
P.S。使用接口,我仍然需要实现bark()
和fly()
,所以这是不可能的,因为我也想重用实现。
P.S.S。使用继承也不是首选,因为它将限制Barkable
和Flyable
模块化。
P.S.S.S。组成不会在运行时更改。
谢谢!
似乎Mixins正是您想要的东西:https://www.typescriptlang.org/docs/handbook/mixins.html