以类型实现抽象类

时间:2018-07-02 12:55:05

标签: typescript typing

我想为我的课程的属性定义类型:

abstract class CoolStuff {
    protected abstract service: any;
}

此服务也是抽象的:

abstract class BaseService<T,K> {
     // Code
}

所以我希望这样:

abstract class CoolStuff {
    protected abstract service: BaseService
}

但是编译器希望我定义TK。但是这些已在实现的服务中定义:

class ActualService extends BaseService<Collection, Model>{
    // Code
}

所以我想做的是以下事情:

abstract class CoolStuff {
    protected abstract service: instanceof BaseService;
}

但是如何?

1 个答案:

答案 0 :(得分:2)

执行此操作的最佳方法是也使CoolStuff通用,然后可以在CoolStuff的派生类中指定实际类型

abstract class CoolStuff<T, K> {
    protected abstract service: BaseService<T, K>;
}

class CoolStuffWithActualService extends CoolStuff<Collection, Model> {
    protected service: ActualService
}

any中将CoolStuff指定为类型参数也可能会避免,但是这会导致基类的键入较弱,因为它可以将任何内容传递给BaseService一个问题。

abstract class CoolStuff {
    protected abstract service: BaseService<any, any>;
}

class CoolStuffWithActualService extends CoolStuff {
    protected service: ActualService
}

修改

第三个选择是将服务类型本身作为CoolStuff的类型参数,并将其限制为BaseService<any, any>类型

abstract class CoolStuff<TService extends BaseService<any, any>> {
    protected abstract service: TService
}

class CoolStuffWithActualService extends CoolStuff<ActualService> {
    protected service!: ActualService
}