-
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
Narrow length of tuples #33182
Comments
I think one of the problems is that you can have an "array" of length 9001, but myArr = []
myArr.length = 9001
alert(myArr.length)
alert("1337" in myArr) 9001 Whereas, with a tuple type, if it had length 9001, it will have all keys from 0 till 9000, inclusive of both |
@AnyhowStep What problems are caused (with regards to this feature request) by JavaScript supporting sparse arrays? I recognize that sparse arrays can certainly cause problems, but that seems to be true unrelated to this feature request. |
Looks like the problem here is that declare function bytesToInt(
bytes: (Array<number> | [number]) & { length: 4 }
): number;
bytesToInt([1, 2, 3, 4]); // okay
bytesToInt([1]); // error!
bytesToInt([1, 2, 3]); // error!
bytesToInt([1, 2, 3, 4, 5]); // error! so you can get the generic length version like this; declare function genericBytesToNum<L extends number>(
length: L,
tuple: (Array<number> | [number]) & { length: L & {} } // noinfer
): number;
genericBytesToNum(2, [1, 2]); // okay
genericBytesToNum(2, [1, 2, 3, 4]); // error
genericBytesToNum(0, []); // okay
genericBytesToNum(0, [1, 2, 3, 4]); // error
genericBytesToNum(4, [1, 2, 3, 4]); // okay
genericBytesToNum(4, [1, 2, 3, 4, 5]); // error Note that without that |
Search Terms
tuple length narrow
Suggestion
Narrow the
length
property on tuple types when used as an Array.Use Cases
Often times a method expects an array of some particular length. This can be expressed as
[T, T, T]
where the number of tuple items is the length of the array. However, sometimes the length is itself generic and in order to properly constrain the type you need to type the parameter asArray<T> & {length:L}
. The problem with this is that if you have a tuple of length L, the compiler still assumes that thelength
is of typenumber
.It would be useful if a tuple type correctly narrowed the type of
length
to be the number of elements in the tuple. This way you could pass a tuple into a method that expects a fixed length array without casting.Examples
Checklist
My suggestion meets these guidelines:
It would be super cool if TypedArrays could get this behavior, since their
length
is fixed at construction time. I'm not sure exactly how to achieve this, so I'll leave it out of this suggestion but if it is possible fornew Uint8Array(4)
to result in a typeUint8Array & {length:4}
that would be great.The text was updated successfully, but these errors were encountered: