google / google/closure-compiler
Ensuring all cases of an enum are handled
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
(This is a feature request.)
Would it be possible to have the compiler type check uses of an enum to ensure that all cases are handled? For example, say that you have a switch statement like this:
``` js
/**
* @param {SomeEnum!} e
* @return {number}
**/
function foo (e) {
switch (e) {
case SomeEnum.A: return 1;
case SomeEnum.B: return 2;
}
}
```
Right now that will warn about not returning a number in all cases. So one solution is to tack on a default case throwing an error:
``` js
function foo (e) {
switch (e) {
...
default: throw new Error(...);
}
}
```
But this means that if the enum is ever changed to add a new case (common for something like, say, an enum of compression methods), the above will throw an error at run time instead of complaining at compile time.
Would it be possible to have the compiler somehow enumerate the cases of the enum and ensure that all the cases are handled, and if so, not warn about a missing return value?
Perhaps this could be enabled by a flag to the compiler or a special jsdoc, though I think in the long term, it would be a good default behavior.
I don't think this would be easy, but it would be a really awesome feature IMO.
Contributor guide
Assessment
This issue has not been assessed yet.