我最多有3个班级:
abstract class Params {
protected params = {};
protected constructor() {}
}
abstract class ListParams extends Params {
protected constructor() {
super();
}
setSkip(skip: number): ListParams {
this.params['skip'] = skip;
return this;
}
}
class MyEntityParams extends ListParams {
constructor() {
super();
}
setTitle(title: string): MyEntityParams {
this.params['title'] = title;
return this;
}
}
我希望能够链接这样的方法:
const myEntityParams = new MyEntityParams();
myEntityParams
.setSkip(0)
.setTitle('HelloWorld');
由于setParams()
return ListParams
,我无法调用setTitle()
它。我可以使用泛型作为返回值来使此示例工作吗?如果是,怎么办?setSkip()
应该返回MyEntityParams
课程。any
实际上,将其用作返回值并不是一种选择,因为在这种情况下,缺少自动补全功能。
您需要使用多态this
作为返回类型:
abstract class Params {
protected params: Record<string, any> = {};
protected constructor() {}
}
abstract class ListParams extends Params {
protected constructor() {
super();
}
setSkip(skip: number): this {
this.params['skip'] = skip;
return this;
}
}
class MyEntityParams extends ListParams {
constructor() {
super();
}
setTitle(title: string): this {
this.params['title'] = title;
return this;
}
}
const myEntityParams = new MyEntityParams();
myEntityParams
.setSkip(0)
.setTitle('HelloWorld');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句