-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
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 as Array<T> & {length:L}. The problem with this is that if you have a tuple of length L, the compiler still assumes that the length is of type number.
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
declare function bytesToInt(bytes: Array<number> & {length:4}): number
bytesToInt([1,2,3,4]) // currently errors, would be nice if it didn't.
bytesToInt([1,2,3,4] as Array<number> & {length:4}) // error prone and something the compiler could do for you.Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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 for new Uint8Array(4) to result in a type Uint8Array & {length:4} that would be great.