-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
'in' expression should be a type guard #1427
Comments
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 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 |
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. |
@danquirk This problem that @jeffreymorlan points out applies to property accesses as well. |
We should look at how prevalent this "assume X based on presence of Y" pattern is in real code. |
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 . |
closing in favor of #10485 |
The in operator provides an opportunity for us to narrow a type. There are two ways that this could work:
The text was updated successfully, but these errors were encountered: