Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast not required in typescript when using instanceof?

I am using instanceof to check if an object is of a certain type. I would expect that if this is true, I'd still need to cast that object to that certain type before I can use it as such.

But instead, inside the IF statement a cast seems not to be necessary. At least not in Visual Studio Code and in the Typescript Playground.

class Drink { 
    price: number = 4;
}

class Beer extends Drink { 
    alcohol: number = 6;
}

let array: Array<Drink> = new Array<Drink>();
array.push(new Drink(), new Beer(), new Drink());

for (let g of array) { 
    // here, only 'price' is available as a property of drink
    console.log(g.price);
    if (g instanceof Beer) {    
        // but unexpectedly, inside the IF statement
        // the alcohol value IS available!
        console.log(g.alcohol);

        // I expected I needed to cast drink to beer first:
        console.log((<Beer>g).alcohol);  
    }
}

Is this very smart behavior of the Typescript editor or is this a glitch?

Copy>Paste the above code in the Typescript Playground to see this behavior...

like image 519
Kokodoko Avatar asked Jun 30 '26 17:06

Kokodoko


1 Answers

As far as I remember this is the Type Guards, available since v1.4:

Type Guards

A common pattern in JavaScript is to use typeof or instanceof to examine the type of an expression at runtime. TypeScript now understands these conditions and will change type inference accordingly when used in an if block.

like image 159
TSV Avatar answered Jul 03 '26 08:07

TSV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!