Disambiguating Tuples from Homogenous Arrays
type ElementType1<T extends any[]> = T[number]; type ArrayElement1 = ElementType1<number[]>; type TupleElement1 = ElementType1<[number, string]>; type ElementType2<T extends any[]> = number extends T["length"] ? { arrayOf: T[number] } : { tuple: T } type ArrayElement2 = ElementType2<number[]>; type TupleElement2 = ElementType2<[number, string]>;
When working with array types, it's a fairly common use case to get the type of the element. The simplest option is the first element type above, T[number] where TypeScript will index into the array type with number. This works for homogenous arrays easily, but for tuples it unions all of the possible element types together.
However, there may be cases where homogenous arrays and tuples should be treated differently. For tuples, TypeScript overrides the .length property with a literal indicating the number of elements. This can be used to disambiguate between the two, by checking if number extends T["length"].












