I would like a rule that switch statements operating on an enum property should fully exhaust the enum, either by a case for all values or by a default case.
enum Number {
one,
two,
three,
}
const obj = {enumerable: Number.one};
// ok
switch (obj.enumerable) {
case Number.one:
case Number.two:
case Number.three:
console.log('number');
}
// ok
switch (obj.enumerable) {
case Number.one:
default:
console.log('number');
}
// not ok
switch (obj.enumerable) {
case Number.one:
case Number.two:
console.log('number');
}
It's a good idea, but it's impossible to enumerate values in an enum for const enums.
A rule could be made that enforces it for standard enums, but it seems a little messy to have a rule that only works depending on the type of enum.
Edit: Actually, I take that previous remark back. Since tslint runs on the TypeScript files, the full definition of the enum is always available no matter which kind of enum it is. However, we'd have to go through with this idea first: https://github.com/palantir/tslint/issues/680
yeah, this rule sounds nice, but as @JKillian mentioned, all rules that require type introspection are blocked on #680 in order to be implemented properly (if you did it just on a per-file basis, the lint rule would be woefully incomplete)
Could this include an exception to switch-default when all cases of the enum are exhausted? Also now that #680 has been implemented by #1363, can this be revisited?
Yep, this can definitely be revisited. Accepting PRs
this thread is pretty stale, but it would be a great addition!
Smth has changed here? As I think this is very great rule to add. This works great in languages like Elm, where we just need to cover all cases, or at least add default. It would mostly help in refactoring when we add new elements to enum, then every switch not covering it would be highlighted.
We've made this simple workaround which has worked really well for us, although not exactly what OP requests:
const unreachable = (v: never): never => {
return v
}
enum Foobar {
foo = 'foo',
bar = 'bar',
}
const getFoobar = (v: Foobar) => {
switch (v) {
case Foobar.foo:
return 'Foo!'
default:
return unreachable(v) // TypeScript error: Argument of type 'Foobar.bar' is not assignable to parameter of type 'never'.
}
}
TSLint is being deprecated and no longer accepting pull requests for new rules. See #4534. ๐ฑ
If you'd like to see this rule implemented, you have two choices:
๐ It was a pleasure open sourcing with you!
_If you believe this message was posted here in error, please comment so we can re-open the issue!_
Most helpful comment
this thread is pretty stale, but it would be a great addition!