我有以下界面
export interface Parent {
some_foo: string,
some_function(some_param): Promise<void>
}我有以下两个实现
export class ChildOne implements Parent {
constructor(some_foo) {
this.some_foo = some_foo
this.another_var = "one"
}
some_function(some_param) {
// some logic using this.some_foo, this.another_var and some_param
}
}
export class ChildTwo implements Parent {
constructor(some_foo) {
this.some_foo = some_foo
this.another_var = "two"
}
some_function(some_param) {
// EXACT SAME logic using this.some_foo, this.anothervar, some_param
}
}我面临的问题是,ChildOne和ChildTwo对于some_function (和其他函数)有完全相同的代码,它们只有通过构造函数才不同。
问题:
PS:我有一个基于参数的工厂方法,它返回ChildOne或ChildTwo的实例
发布于 2021-12-05 23:59:51
您可以使用混和,它允许您使用组合而不是继承应用抽象实现:
interface Parent {
some_foo: string;
some_function(some_param): Promise<void>;
}
// utility type so that we can use the parent interface minus the function to be mixed-in
type PartialParent = Omit<Parent, 'some_function'>;
// define the implemting class without some_function
class PartialChildOne implements PartialParent {
some_foo: string;
another_var: string;
constructor(some_foo: string) {
this.some_foo = some_foo;
this.another_var = 'one';
}
}
class PartialChildTwo implements PartialParent {
some_foo: string;
another_var: string;
constructor(some_foo: string) {
this.some_foo = some_foo;
this.another_var = 'two';
}
}
// we can provide constraints for our mixin - see below
type HasAnotherVar = { another_var: string };
// define the constraints - must be a class, must be PartialParent AND satisfy HasAnotherVar
type Constructor<T = {}> = new (...args: any[]) => T;
type PartialParentConstructor = Constructor<PartialParent & HasAnotherVar>;
// here we apply the abstract function we need - taken from the ts docs - https://www.typescriptlang.org/docs/handbook/mixins.html
function applySomeFunction<TBase extends PartialParentConstructor>(
Base: TBase
) {
return class WithSomeFunction extends Base {
async some_function(some_param: string): Promise<void> {
console.log(this.some_foo, this.another_var, some_param);
}
};
}
// then we can apply the mixin to create composed classes, which each have some_function defined
const ChildOne = applySomeFunction(PartialChildOne);
const ChildTwo = applySomeFunction(PartialChildTwo);
// use the classes
const c1 = new ChildOne('foo');
const c2 = new ChildTwo('bar');
// typescript is totally happy with this
c1.some_function('hello');
c2.some_function('goodbye');
// and the classes meet the `Parent` interface so typescript is happy with this casting as well
let asParent = c1 as Parent;
asParent = c2 as Parent;https://stackoverflow.com/questions/70239356
复制相似问题