4

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?

1 Answer 1

3

Yes, TypeScript supports type casting. You should be able to do:

if(typeof x.A === 'string'){
    console.log((<L>x).STR);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm. That doesn't seem to work. Casting would work if I had a variable that was already declared as type L, as in: var x:L; x = <L>FUN(); . But doesn't re-cast x once it's already defined (var'd).
Oops, you're right. I needed some parenthesis. I edited my answer. Give that a try.
Thanks so much! Solved my problem and I learned an new usage for the type assertion!
No problem. Glad I was able to help you out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.