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.
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).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
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:
U defaults to ',' to match JavaScript's Array.join() behavior when no separator is provided, as demonstrated by the test case Join<['1', '1', '1']> expecting '1,1,1'.infer First extends string to ensure it is treated as a string type in template literals.Rest is empty (i.e., we are on the last element), we return just First without appending a trailing separator.First, the separator U, and the recursive result of Join<Rest, U> to build up the joined string.[] returns the empty string ''.U can be either a string or number type (e.g., 1), which works naturally in template literal interpolation (${1} produces "1").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.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.