type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-tuple-to-union

Open utterances-bot opened this issue 3 years ago • 6 comments
trafficstars

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

utterances-bot avatar Apr 08 '22 23:04 utterances-bot

Has T[number] ever been documented as a valid lookup type? I don't see it in the link to Lookup Types.

michaeljsalo avatar Apr 08 '22 23:04 michaeljsalo

@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.

ghaiklor avatar Apr 09 '22 07:04 ghaiklor

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 avatar Apr 09 '22 15:04 michaeljsalo

@michaeljsalo don't see any reasons why you can't pass T[string], play around with it 😉

ghaiklor avatar Apr 10 '22 07:04 ghaiklor

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?

daniel-hyun-chae avatar Nov 08 '22 17:11 daniel-hyun-chae

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

daniel-hyun-chae avatar Nov 08 '22 17:11 daniel-hyun-chae