You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I'm trying to make use of the new "mappable tuple and array types" coming in 3.1, and discovered that it's a bit awkward to work with arrays constrained to a particular type.
The issue here is that even though a homomorphic mapped type only maps the element type(s) of the array or tuple, keyof A still includes the non-numeric properties of Array<T> (i.e. "length", "concat", etc.) and therefore A[keyof A] (the constraint of A[K]) is a large and fairly useless union type that can't be indexed with "foo".
We considered having keyof T for an array or tuple type not include non-numeric properties, but it would be a significant breaking change. For example, A["length"] wouldn't work anymore.
Given where we're at, your conditional type workaround seems reasonable.
When mapping over the keys K in a type T constrained to an array type, is it possible to narrow K instead of T or keyof T? Assuming there were a "numericString" type, the suggestion is to treat
That would possibly give the expected behavior here without pretending that keyof T is limited to the numeric keys, so T['length'] would still exist. Just a passing thought...
TypeScript Version: 3.1.0-dev.20180925
Search Terms: mappable tuples constraints covariance
I'm trying to make use of the new "mappable tuple and array types" coming in 3.1, and discovered that it's a bit awkward to work with arrays constrained to a particular type.
Code
Expected behavior:
Should compile.
Actual behavior:
Error:
Type '"foo"' cannot be used to index type 'A[K]'.
.Notes
It's possible to work around this using a conditional:
but it seems like it should just work as is.
Playground Link
The text was updated successfully, but these errors were encountered: