Improve typings of Array.map when called on tuples
See original GitHub issueSearch Terms
- Array.map
- map tuple
Suggestion
Using Array.map on a tuple should return a tuple instead of an array. In one of my projects I could achieve that using
declare interface Array<T> {
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): { [K in keyof this]: U };
}
I haven’t encountered any negative side effects.
Use Cases
This can be useful when you want to use tuples as a fixed length array.
Examples
type Vec3D = [number, number, number];
let vec: Vec3D = [1, 2, 3];
let scaledVec: Vec3D = vec.map(x => 2 * x);
This is currently an error: https://www.typescriptlang.org/play/#src=type Vec3D %3D [number%2C number%2C number]%3B let vec%3A Vec3D %3D [1%2C 2%2C 3]%3B let scaledVec%3A Vec3D %3D vec.map(x %3D> 2 * x)%3B
But with the proposed change it would not be an error: https://www.typescriptlang.org/play/#src=declare interface Array<T> { map<U>(callbackfn%3A (value%3A T%2C index%3A number%2C array%3A T[]) %3D> U%2C thisArg%3F%3A any)%3A%20%7B%20%5BK%20in%20keyof%20this%5D%3A%20U%20%7D%3B%0D%0A%7D%0D%0A%0D%0Atype%20Vec3D%20%3D%20%5Bnumber%2C%20number%2C%20number%5D%3B%0D%0Alet%20vec%3A%20Vec3D%20%3D%20%5B1%2C%202%2C%203%5D%3B%0D%0Alet%20scaledVec%3A%20Vec3D%20%3D%20vec.map(x%20%3D%3E%202%20*%20x)%3B
Checklist
My suggestion meets these guidelines:
- This wouldn’t be a breaking change in existing TypeScript/JavaScript code (At least I think so…)
- 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.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:48
- Comments:9 (3 by maintainers)
Top GitHub Comments
After updating 45kloc to
noUncheckedIndexedAccess = true
, indeed having this feature would increase type safety significantly in our case.If it helps, here’s another use-case:
In the last line there is an error: stringCompare expects 2 arguments, but gets 0+.
There’s also many more use-cases when --noUncheckedIndexedAccess is enabled.