#5310Medium

Join

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. Learn array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the type-level version of Array.join, creating a Join<T, U> type that concatenates tuple elements into a single string type with a separator.

Challenge Instructions: Join

Medium

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"], "-">; // expected to be 'a-p-p-l-e'
type Res1 = Join<["Hello", "World"], " ">; // expected to be 'Hello World'
type Res2 = Join<["2", "2", "2"], 1>; // expected to be '21212'
type Res3 = Join<["o"], "u">; // expected to be 'o'

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<Join<['a', 'p', 'p', 'l', 'e'], '-'>, 'a-p-p-l-e'>>,
  Expect<Equal<Join<['Hello', 'World'], ' '>, 'Hello World'>>,
  Expect<Equal<Join<['2', '2', '2'], 1>, '21212'>>,
  Expect<Equal<Join<['o'], 'u'>, 'o'>>,
  Expect<Equal<Join<[], 'u'>, ''>>,
  Expect<Equal<Join<['1', '1', '1']>, '1,1,1'>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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

How it works:

This challenge helps you understand recursive template literal type construction and tuple processing, and how to apply these techniques in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts