GeezerVison is showing github.com — consider allowing exhaustive switch statement · Issue #6155 · microsoft/TypeScript
consider allowing exhaustive switch statement #6155Descriptiontype 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
}Reacted by Tingan Ho, Ceyhun Can Ulker, Daniel M., Kris Kaczor and Bruno Lemos ActivityzpdDG4gta8XKpMCd commented on Dec 18, 2015 (it's up to the developer to take the responsibility for possible contract violations at runtime) weswigham commented on Dec 18, 2015 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. zpdDG4gta8XKpMCd commented on Dec 18, 2015 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 zpdDG4gta8XKpMCd commented on Dec 18, 2015 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? zpdDG4gta8XKpMCd commented on Dec 18, 2015 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). RyanCavanaugh commented on Dec 18, 2015
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. mhegazy commented on Feb 19, 2016 with #7140 in place we should be able to make better decisions here. zpdDG4gta8XKpMCd commented on Feb 19, 2016 I am super excited to welcome non-nullables, but exhaustive switches are a different beast isn't it? ahejlsberg commented on Jun 29, 2016 Checking for exhaustive switch statements is now possible with #9407. zpdDG4gta8XKpMCd commented on Jun 29, 2016 best day ever! thanks a bunch
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|