【问题标题】:type check with typescript interface inheritance使用 typescript 接口继承进行类型检查
【发布时间】:2020-09-03 08:43:14
【问题描述】:

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

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,因为它们不是类,它们是实现接口的对象。但是有没有一种方法不需要像我在类型保护中那样手动检查每个属性?

【问题讨论】:

    标签: typescript inheritance interface


    【解决方案1】:

    由于接口在编译时被擦除,因此没有关于它们的运行时信息,因此没有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;
    }
    

    这样每个实现都负责调用LayerDataService 上的相关函数,这无疑增加了开销。我不完全确定这是否适用于您的情况,但我认为值得一提。

    【讨论】:

    • 是的,可以。我采取了另一种方式,那就是将我的接口转换为类。我会发布答案
    【解决方案2】:

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

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

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

    【讨论】:

    • 这将需要我在警卫中手动检查接口的每个属性,这似乎有点多余,因为我已经定义了接口本身。如果我更改我的接口,我还需要更改两次,一次在接口定义中,一次在类型保护中。所以基本上复制了接口定义。我希望有更好的方法。类似于instanceof
    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 2023-03-22
    • 2019-06-25
    • 1970-01-01
    • 2021-05-13
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多