-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Weak type guaranties for tuples #15656
Comments
One more example: type Vector2d = [number, number];
const v: Vector2d = [1, 2, 3];
console.log(v[3].toString()); // throws an exception |
Tuples are now fixed length, but we've opted to leave the array methods in place for compatibility reasons |
Oh and |
@RyanCavanaugh Is there somewhere I can read more discussion on this? This seems like an easy win for soundness (tuples not allowing |
TypeScript Version: 2.3.2
I bumped into a strange behaviour wrt tuples by spotting a difference in the way type inference works with value and reference types.
Code
This is understandable, because
const
/readonly
work the same way as their JS equivalents (values of reference types are mutable), so casting to the most specific type without having a way of enforcing actual immutability would cause more harm than good.At that point I expected that explicitly typing my tuples as
[number, number]
will not only make the compiler comply (no morenumber[]
is not assignable to[number, number]
), but also give me additional type guarantees. Then I discovered that I can do the following no problem:Expected behaviour:
There are probably 2 things that could be done here:
Array.prototype
methods are disallowed on tuples. Virtually all of them, when called on a tuple, guarantee that you're going to end up with a value incompatible with your tuple type. The exception would be calling them with arguments that do nothing (e.g.[1, 2].splice(0, 2)
) and calling those which add and element (e.g.[1, 2].push(3)
).Actual behaviour:
Tuples behave like arrays with only minimum length being enforced.
The text was updated successfully, but these errors were encountered: