创建具有接口A和接口B的所有属性的类型

时间:2017-05-24 11:19:02

标签: typescript

我希望myValue属于interface Ainterface B

interface interfaceA {
  commonProp: any;
  specificToA: any;
}

interface interfaceB {
  commonProp: any;
  specificToB: any;
}


let myValue: interfaceA | interfaceB;

myValue.interfaceA // doesn't work, I only have access to commonProp

我如何让myValue有权访问specificToAspecificToB

1 个答案:

答案 0 :(得分:1)

您可能想要使用type guards

function isA(arg: any): arg is interfaceA
{
    return 'specificToA' in arg;
}

if (isA(myValue))
{// Here typescript will know you are dealing with interfaceA
    let v = myValue.specificToA;
}