The following code is the gist of what I'm trying to do
enum Foo {
Foo0, Foo1, Foo2, Foo3, Foo4 // many more
}
function bar(foo: Foo) {
const baz: [any, any] = [0,0];
// Only Foo0 and Foo1 are valid to pass to bar
if(foo > 2) throw RangeError();
return baz[foo];
// ^ Linter gives the following, even though foo can't be greater than 2:
// TS2493 [ERROR]: Tuple type '[any, any]' of length '2' has no element at index '2'.
// TS2493 [ERROR]: Tuple type '[any, any]' of length '2' has no element at index '3'.
// TS2493 [ERROR]: Tuple type '[any, any]' of length '2' has no element at index '4'.
}
Because of the line checking the value of foo
, baz[foo]
will never be greater than 2. Is there any way I can convince Typescript that it doesn't need to worry about that?
Because enum
keys can be associated with any value, i.e. they do not have to be ascending numbers or start at one specific number, and the compiler does not provide the concrete values there seems to be no way to cleanly handle this.
I would recommend to assert that foo is a number and use that (though that still leaves potential for errors):
function bar(foo: Foo) {
const baz: [any, any] = [0,0];
const index = foo as number;
if (index > 1) throw RangeError(); // if enum is 0-based (default)
return baz[index];
}