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

时间:2020-06-29 12:20:28

标签: typescript generics

我最多有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()返回了ListParams,因此我无法在其上调用setTitle()。我可以使用泛型作为返回值来使此示例工作吗?如果是,怎么办? setSkip()应该返回MyEntityParams类。实际上,不能使用any作为返回值,因为在这种情况下,缺少自动补全功能。

1 个答案:

答案 0 :(得分:1)

您需要使用polymorphic 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');

Playground Link

相关问题