TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

'in' expression should be a type guard

Open JsonFreeman opened this issue 11 years ago • 6 comments

The in operator provides an opportunity for us to narrow a type. There are two ways that this could work:

  1. We can select particular constituents of a union type based on which members are present:
interface I1 {
    p: string;
}
interface I2 {
    q: string;
}

var v: I1 | I2;
if ("p" in v) {
    v.p; // Error
}
  1. If we have a general type like Object, we can clone the type and add a specific property to it when narrowing:
var v: Object;
if ("p" in v) {
    v.p; // Type should be { p: any }
}

JsonFreeman avatar Dec 10 '14 02:12 JsonFreeman

There's a hidden trap inherent in using property existence to distinguish the types in a union: imagine if elsewhere in the code there is a type interface I2Ext extends I2 { p: number; }, and an I2Ext makes its way into the function that uses p to distinguish I1 | I2. Any time you extend a type and add a property you'd have to worry about whether the name you picked will cause it to be misidentified somewhere...

This could be made safe if there were a way to specify that an object lacks a certain property, and that were used to determine which parts of a union get narrowed away when in evaluates to true.

jeffreymorlan avatar Dec 10 '14 03:12 jeffreymorlan

Yes, that is a great point. I think the crux of it is that you can't eliminate a constituent based on the fact that it lacks a property you observe to be present. But as you alluded to, if there were an else block, it would be safe to narrow there based on the observation that a property is absent.

JsonFreeman avatar Dec 10 '14 18:12 JsonFreeman

@danquirk This problem that @jeffreymorlan points out applies to property accesses as well.

JsonFreeman avatar Dec 10 '14 18:12 JsonFreeman

We should look at how prevalent this "assume X based on presence of Y" pattern is in real code.

RyanCavanaugh avatar Dec 17 '14 19:12 RyanCavanaugh

Today we would have:

interface I1 {
    prop1: string;
    doSomething(): string;
}
interface I2 {
    prop2: string;
    doAnotherThing(): string;
}
class MyObject implements I2 {
    prop1: string = "";
    prop2: string = "";
    doAnotherThing() {
        return 'doAnotherThing';
    }
    doSomething() {
        return 'doSomething';
    }
}
function test(obj: I1 | I2) {
    if ('prop1' in obj) {
        alert('doSomething() = ' + (<I1> obj).doSomething());
    } else {
        alert('doAnotherThing() = ' + (<I2> obj).doAnotherThing());
    }
}

test(new MyObject);

As there's no type guard, I just type cast. I believe having 'in' as type guard is no more dangerous than a typecast. It's even a little better, perharps .

awerlang avatar Jan 26 '15 18:01 awerlang

closing in favor of https://github.com/Microsoft/TypeScript/issues/10485

mhegazy avatar Sep 20 '16 20:09 mhegazy