All
Less than 1 minuteTC-Medium
All
Problem
Returns true if all elements in the list are equal to the second parameter, false if there are any mismatches.
type Test1 = All<[1, 1, 1], 1> // true
type Test2 = All<[1, 1, 2], 1> // false
type Test3 = All<[1, 'two', 1], 1> // false
type Test4 = All<[1, 1, 1], 1 | 2> // false (distribution)
type Test5 = All<[], 1> // true (vacuously)Solution
type All<T extends any[], U> =
T extends [infer First, ...infer Rest]
? [First] extends [U]
? [U] extends [First]
? All<Rest, U>
: false
: false
: trueHow it works:
- Recursively peel the first element off the tuple.
- Use the double-
extendstrick ([First] extends [U]and[U] extends [First]) to check exact equality — wrapping in[]prevents distributive conditional types. - If both directions hold, the element matches
U; recurse on the rest. - An empty tuple returns
true(vacuous truth).
Key Takeaways
[X] extends [Y]suppresses distribution, giving an exact bidirectional assignability check.- Recursive tuple traversal with
[infer First, ...infer Rest]is the standard pattern for checking every element. - An empty base case returning
trueis the correct "vacuously true" semantics.
