How to convert a tuple type to a union?
Asked Answered
A

1

17

How to map a tuple generic type to a union type?

type NeededUnionType<T> = T[keyof T]; // Includes all the Array properties values
  
const value: NeededUnionType<[7, string]> = 2; // This should not be allowed (2 is the tuple length)

Expected type: 7 | string

Aeropause answered 8/12, 2019 at 20:30 Comment(1)
type UnionFromTuple = TupleType[number];Bereave
X
29

You can index by number instead of keyof T. keyof T will contain all keys of the tuple object which includes the length as well as any other array properties.

type NeededUnionType<T extends any[]> = T[number]; // Includes all the Array properties values

const value: NeededUnionType<[7, string]> = 2; // err value is 7 | string 

Playground Link

Xylem answered 8/12, 2019 at 20:38 Comment(2)
Is T[number] as a means to query all array members documented? Does this imply other expressions are possible, like T[string] to query all object members?Bastinado
@Bastinado Consider this documentation and see if you figure it out :)Ahvenanmaa

© 2022 - 2024 — McMap. All rights reserved.