type-challenges-solutions
type-challenges-solutions copied to clipboard
type-challenges-solutions/en/medium-tuple-to-union
Tuple to Union
This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.
https://ghaiklor.github.io/type-challenges-solutions/en/medium-tuple-to-union.html
Has T[number] ever been documented as a valid lookup type? I don't see it in the link to Lookup Types.
@michaeljsalo it is worth looking into Indexed Access Type as well (https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html). There are no restriction on what the type you can pass there, so... you can pass a number too.
If it's an indexed access type, does this imply an index like T[string] is possible, to get values out of an object?
@michaeljsalo don't see any reasons why you can't pass T[string], play around with it 😉
I was expecting that "T extends unknown[]" does not express tuple correctly because an array of certain type e.g. string[] can be consisted only of string. Whereas, tuple can contain multiple types. I was rather expecting something like "T extends [...any]". But at the same time, I'm surprised that type TupleToUnion<T extends unknown[]> = T[number] can accept "[123, '456', true]" as T.. Can anyone explain why this is possible?
My solution of expressing tuple slightly differently.
type TupleToUnion<T extends [...unknown[]]> = T[number]
https://www.typescriptlang.org/docs/handbook/2/objects.html#tuple-types