首页 > 解决方案 > 检查json属于哪个扩展接口

问题描述

我有一个由其他两个接口扩展的父接口

interface ParentItem {
  foo: number;
}

interface ChildItemOne extends ParentItem {
  fooone: string;
}

interface ChildItemTwo extends ParentItem {
  footwo : string;
}

我有一个接受 ParentItem 的函数,我如何确定它是属于 ChildItemOne 还是 ChildItemTwo

if(obj.footwo) or if(obj.fooone) // obj = ParentItem obj导致错误,因为 footwo 或 fooone 不是 ParentItem 的一部分

标签: typescript

解决方案


你可以这样做:

在操场上测试

使用联合类型ChildItemOne | ChildItemTwo作为参数并检查一个属性是否是对象的一部分......

function suggestion1 (baz: ChildItemOne | ChildItemTwo) {
    if('fooone' in baz) {
        baz.fooone;
        // baz is ChildItemOne
    } else {
        baz.footwo;
        // baz is ChildItemTwo
    }
}

...或使用泛型类型ParentItem作为参数并定义类型保护函数。

function suggestion2 (baz: ParentItem) {
    if(isItemOne(baz)) {
        baz.fooone;
    } else if(isItemTwo(baz)) {
        baz.footwo;
    }
}

function isItemOne (obj: ParentItem): obj is ChildItemOne {
    return 'fooone' in obj;
}

function isItemTwo (obj: ParentItem): obj is ChildItemTwo {
    return 'footwo' in obj;
}

推荐阅读