Lev
Lev

Reputation: 15734

create type that has all properties of interface A and interface B

I want myValue to be of type interface A or interface 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

How can I have myValue have access to specificToA and specificToB ?

Upvotes: 2

Views: 35

Answers (1)

Amid
Amid

Reputation: 22382

You probably want to use 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;
}

Upvotes: 1

Related Questions