Evaluate mathematical expression of indices when indexing tuples #42693
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
π Search Terms
tuple bounds, tuple index computing, bound checking removal, noUncheckedIndexedAccess
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
Currently (version 4.1), Typescript is able to deduce that an array access to a tuple is within bounds if it is indexed by an integer literal union type that fits within the array, e.g.:
However, as soon as there is an operation on the indexing variable, even trivial, Typescript falls back to inferring
number
. Therefore, the following code:In principle, Typescript could reason a bit deeper on the set of possible integer values when going through operations, especially for the trivial ones like in my example. If there is a lot of values in the union, it might be computationally expensive, but in that case a conservative bound analysis would already be enough for most uses cases (see #15480).
π Motivating Example
The proposed feature would at minimum allow:
and, if possible, use cases such as:
and, if
Vector
andMatrix
can be aliases to fixed-size typed arrays (see #18471) in addition to tuple, it would be wonderful.π» Use Cases
That feature would be very useful in conjunction with
noUncheckedIndexedAccess
obviously, but also with a way to statically type the length ofTypedArray
(see #18471) for use in mathematical and graphics code. But even without typed arrays, it would still be useful in day-to-day code. I'm experimenting in switching our 45 kloc Typescript code base tonoUncheckedIndexedAccess = true
and that feature would increase type safety in several places.The text was updated successfully, but these errors were encountered: