consider allowing exhaustive switch statement
Closed this issue · 10 comments
type foo = 'hey' | 'nay';
let value : foo = 'hey';
switch (value) {
case 'hey': doThis(); break;
case 'nay': doThat(); break;
default: void; // <-- syntax TBD that indicates: 1. no other than known options are allowed 2. all known options must be considered
}
(it's up to the developer to take the responsibility for possible contract violations at runtime)
The default
branch in your example can be triggered when value
is undefined
or null
as both let value : foo = null;
and let value : foo = undefined;
are valid for type foo
.
since we are going exhaustive here, and there is no way to ask the type system to prevent those 2 from popping up, let's require the developer to take care of them explicitly:
case undefined: doSomethingElse(); break;
case null: void; // <-- instructing the compiler to chill
slippery moment here is that the undefined
is just a variable, not a literal, but hey, why would you want to mess with it? anyway the emitter can take care of it:
case void undefined: doSomethingElse(); break;
By the way, why wouldn't TypeScript stop this nonsense and straiten things up by proclaiming undefined
a literal and thus preventing it from being assigned?
On top of that please admit that Undefined
is a real type that can be referenced as well as Null
. It's never a good idea to depart from what the real world is (I mean JavaScript here) by trying to model it using wrong entities (void type in TypeScript).
TypeScript should stop this nonsense and straiten things up by proclaiming undefined a literal and thus prevent it from being assigned.
This is already the case in strict mode.
As for the null and undefined types, I think we want to keep their names "off limits" until we address nullability as a real language feature and understand the desired semantics there.
I am super excited to welcome non-nullables, but exhaustive switches are a different beast isn't it?
Checking for exhaustive switch statements is now possible with #9407.
best day ever! thanks a bunch