Yuzhe's Blog

yuzhes

Join

Join

Problem Link

Problem

Implement the type version of Array.join, Join<T, U> takes an Array T, string or number U and returns the Array T with U stitching up.

type Res = Join<['a', 'p', 'p', 'l', 'e'], '-'>  // 'a-p-p-l-e'
type Res1 = Join<['Hello', 'World'], ' '>          // 'Hello World'
type Res2 = Join<['2', '2', '2'], 1>               // '2' | '212' | '2122' — wait, actually '2122'
type Res3 = Join<[], 'x'>                           // ''

Solution

Approach: Recursive String Building

Peel elements off one at a time and concatenate with the delimiter.

type Join<T extends string[], U extends string | number> =
  T extends [infer First extends string, ...infer Rest extends string[]]
    ? Rest extends []
      ? First
      : `${First}${U}${Join<Rest, U>}`
    : ''

How it works:

  1. Extract First and Rest from T.
  2. If Rest is empty (last element), return First alone — no trailing delimiter.
  3. Otherwise, prepend ${First}${U} to the recursive result.
  4. Empty array returns ''.

Key Takeaways