I have a function that returns values with one of two interfaces, like so:
interface K {
A:number;
NUM:number;
}
interface L {
A:string;
STR:string;
}
function FUN():K|L { }
var x:K|L = FUN();
but I can't access the non-shared property using a type-guard like this one:
if(typeof x.A === 'string'){
console.log(x.STR) // Property 'STR' does not exist on type 'K | L'
}
even though the if clause does distinguish between the two types. I know I can use as operator with a variable assignment to indicate the type to the compiler like so:
if(typeof x.A === 'string'){
var y = x as L;
console.log(y.STR) // OK
}
but that seems a bit kludgy as this add a unnecessary var statement and assignment in the resulting js code:
function FUN() { }
var x = FUN();
if (typeof x.A === 'string') {
var y = x; // unnecessary...
console.log(y.STR);
}
Is there any way to indicate the type in this situation without the extra var y=x; in the JS code?