Join
Less than 1 minuteTC-Medium
Join
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:
- Extract
FirstandRestfromT. - If
Restis empty (last element), returnFirstalone — no trailing delimiter. - Otherwise, prepend
${First}${U}to the recursive result. - Empty array returns
''.
Key Takeaways
- The last-element check (
Rest extends []) avoids a trailing delimiter — matchesArray.joinsemantics. infer First extends stringconstrains the inferred type directly, avoiding an extra cast.
