具有TypeScript接口继承的类型检查

时间:2020-09-03 08:43:14

标签: typescript inheritance interface

我有一个接口和两个扩展它的接口:

interface Layer {
    name: string;
    pretty_name: string;
}

interface SubLayer extends Layer{
    url: string;
}

interface AnotherLayer extends Layer{
    file: string;
}

然后我有一个服务,该服务具有处理任何Layer参数的函数,然后需要区分子接口并根据以下条件调用正确的函数:

class LayerDataService {

    static getLayer(layer: Layer) {
        if (......) {
            return LayerDataService.getSubLayer(layer as SubLayer );
        }
        else if (......) {
            return LayerDataService.getAnotherLayer(layer as AnotherLayer);
        }
    }

    static getAnotherLayer (layer: AnotherLayer) {

    }
    static getSubLayer(layer: SubLayer) {

    }
}

所以在.....上,我想区分实现SubLayer的层和实现AnotherLayer的层。

所以我知道我不能使用instanceof,因为它们不是类,而是实现接口的对象。但是,有没有一种方法不像我在类型保护程序中那样手动检查每个属性?

2 个答案:

答案 0 :(得分:1)

由于在编译时会擦除接口,所以没有关于它们的运行时信息,因此没有#include<iomanip> #include<iostream> #include<string> int main(){ int lines_number; int turning_point; std::string text; std::cin >> lines_number >> turning_point >> text; int inc_dec = 1; for(int line = 0, spaces = 1; line < lines_number; line++, spaces += inc_dec) { std::cout << std::setw(spaces) << text << std::endl; if((spaces == turning_point) || (spaces == 1 && inc_dec < 0)) { inc_dec *= -1; } } return 0; } 。我能想到的唯一解决方案是反转依赖关系,因此由层来决定其调用方式...

instanceof

这样,每个实现都负责在class LayerDataService { static getLayer(layer: Layer) { layer.get(this); } } interface Layer { name: string; pretty_name: string; get(service: LayerDataService): void; } interface SubLayer extends Layer{ url: string; } interface AnotherLayer extends Layer{ file: string; } 上调用相关函数,这无疑会增加开销。我不确定这是否适合您的情况,但我想一提。

答案 1 :(得分:0)

不确定我是否理解正确,但是您可以使用我认为的类型保护功能。

function (layer: unknown): layer is AnotherLayer {
   return !!layer.file;
}

SubLayer执行相同的操作,则可以将其用作标准函数,但是在括号内将强类型化为指定类型。