Suggestion: Smart casts

Topics: Language Specification
Oct 22, 2012 at 11:37 PM
Edited Oct 22, 2012 at 11:52 PM

We already have type inference, but it'd be great if we also had smart local casts/type inference.

For example:

function example(obj: Interface) {
    if (obj instanceof Class) {
        // instead of having to do:
        // var c: Class = <Class> obj;
        // obj would already have type Class inferred inside the block.

Avoiding the extra variable is not only convenient but should improve runtime performance. Right now, you can only way bypass it casting every reference: (<Class> obj).prop;

Oct 23, 2012 at 3:14 PM

Thanks for the suggestion.  It's something we've considered, though I'm not sure, in the general case, how much overhead adding flow-sensitivity will add to the type inference algorithm. 

I'll copy this to a issue tracker as a feature request. 

Oct 23, 2012 at 3:14 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.