Yuzhe's Blog

yuzhes

All

All

Problem Link

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
    : true

How it works:

  1. Recursively peel the first element off the tuple.
  2. Use the double-extends trick ([First] extends [U] and [U] extends [First]) to check exact equality — wrapping in [] prevents distributive conditional types.
  3. If both directions hold, the element matches U; recurse on the rest.
  4. An empty tuple returns true (vacuous truth).

Key Takeaways