narrow type in else block of if (is...)
See original GitHub issue[@gavinking] Tako gives this example:
shared Integer q(Integer? x) {
if (is Null x) {
return 0;
}
else {
return x; //compile error
}
}
He argues, rather reasonably, that the compiler should be able to reason that x
has type Integer
where the error occurs.
I agree that it would be possible. This would not amount to supporting types like X~Y
, which Ross says results in undecidability, if I recall correctly. It just means being able to utilize the identity X|Y~Y == X
, which we already do utilize in certain places.
On the other hand:
- This example is a bit contrived. It would be much more usual to reverse the condition to do
if (is Integer x)
orif (exists x)
. - For more complex cases, this is stepping on the turf of the
switch
statement.
So I’m not sure that this feature would really be especially practically useful. OTOH, it’s easily doable.
[Migrated from ceylon/ceylon-spec#74] [Closed at 2014-11-17 20:31:44]
Issue Analytics
- State:
- Created 12 years ago
- Comments:86
Top Results From Across the Web
Documentation - Narrowing - TypeScript
In the printAll function, we try to check if strs is an object to see if it's an array type (now might be...
Read more >Learn TypeScript: Type Narrowing Cheatsheet - Codecademy
If a variable is of a union type, TypeScript can narrow the type of a variable using a type guard. A type guard...
Read more >6 ways to narrow types in TypeScript | Building SPAs
In a TypeScript program, a variable can move from a less precise type to a more precise type. This process is called type...
Read more >Typescript type narrowed to never with instanceof in an if-else ...
I have a problem when I try to use instanceof with derived class instances in a if-else statement ...
Read more >narrowing types via type guards and assertion functions - 2ality
TypeScript's type inference supports type guards by narrowing the static type of an operand when the result is true .
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
[@gavinking] And if, for some irrational reason, you want to use
if
instead ofswitch
, you can easily write:Which is to my eyes much clearer than saying that
x
is aFoo
ooooh except where it’s not.[@jvasileff] Oh, cool, this also addresses #4344!