我希望myValue
属于interface A
或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
我如何让myValue
有权访问specificToA
和specificToB
?
答案 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;
}