IsTuple
Less than 1 minuteTC-Medium
IsTuple
Problem
Implement a type IsTuple, which takes an input type T and returns whether T is tuple type.
type case1 = IsTuple<[number]> // true
type case2 = IsTuple<readonly [number]> // true
type case3 = IsTuple<number[]> // falseSolution
Approach: Check for Finite Length
A tuple has a fixed, finite length (a numeric literal), while an array has number as its length.
type IsTuple<T> =
T extends readonly unknown[]
? number extends T['length']
? false
: true
: falseHow it works:
- First confirm
Tis array-like (readonly unknown[]). - Check
T['length']: for arrays it'snumber, for tuples it's a numeric literal like0 | 1 | 2. number extends T['length']istrueonly whenT['length']is exactlynumber— i.e., it's an array, not a tuple.
Key Takeaways
- The key insight:
number extends 3isfalse, butnumber extends numberistrue. readonly unknown[]is the widest array type and accepts both mutable and readonly tuples/arrays.- This pattern — checking whether a length is a literal vs.
number— appears in many tuple-detection scenarios.
