从打字稿中的扩展类返回通用值

沙恩克

我最多有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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章