#33625•Extreme

Join String Union

Collapse a union of string literals into one separated string. The hard part is pulling out a single member at a time, in a stable order.

JoinStringUnion<T, U> takes a union of string literals and a separator and returns one string containing every member.

At runtime this is ['test', 'hello', 'world'].join(', '). In the type system there is no array to walk. A union is an unordered set, and template literal types distribute over it, so the obvious attempt gives you back a union of three one-element strings instead of a single joined one. The tests pin that down: the second and fourth assertions feed the result through UnionToIntersection and fail if it is anything other than a single string.

type Sep = ', '
type Joined = JoinStringUnion<'test' | 'hello' | 'world', Sep>
// one string, for example 'test, hello, world'

Challenge Instructions: Join String Union

Extreme

Join union of string into a string.

View on GitHub: https://tsch.js.org/33625

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

ChallengeSolution
/* _____________ Your Code Here _____________ */

type JoinStringUnion<T, U> = T

/* _____________ Test Cases _____________ */
import type { Expect } from '../helpers'

type Case1 = 'test' | 'hello' | 'world'
type Case2 = '1' | '2' | '3' | '4' | '5'
type Sep = ', '

type cases = [
  Expect<JoinStringUnion<Case1, Sep> extends JoinStringUnionAllPossibilities<Case1, Sep> ? true : false>,
  Expect<[UnionToIntersection<JoinStringUnion<Case1, Sep>>] extends [never] ? false : true>,
  Expect<JoinStringUnion<Case2, Sep> extends JoinStringUnionAllPossibilities<Case2, Sep> ? true : false>,
  Expect<[Uni

Pro Challenge

Get access to all 200+ challenges, including every medium, hard, and extreme one.

One-time payment, lifetime access. 30-day money-back guarantee.

Detailed Explanation

The solution in full:

type ToIntersection<U> = (U extends unknown ? (arg: U) => void : never) extends (
  arg: infer I,
) => void
  ? I
  : never
 
type LastInUnion<U> =
  ToIntersection<U extends unknown ? () => U : never> extends () => infer L
    ? L
    : never
 
type JoinStringUnion<T extends string, U extends string> = [T] extends [never]
  ? ''
  : LastInUnion<T> extends infer Last extends string
    ? [Exclude<T, Last>] extends [never]
      ? Last
      : `${JoinStringUnion<Exclude<T, Last>, U>}${U}${Last}`
    : never

Three pieces: turn a union into an intersection, use that to name one member, then recurse.

Distribution, and why it is the problem here

When the checked type of a conditional is a bare type parameter, TypeScript applies the conditional to each union member separately and unions the results. That is distribution. U extends unknown ? (arg: U) => void : never with U = 'a' | 'b' does not produce (arg: 'a' | 'b') => void. It produces ((arg: 'a') => void) | ((arg: 'b') => void).

Distribution is also why a naive join fails. `${T}${U}` with a union T distributes and yields 'test, ' | 'hello, ' | 'world, '.

Wrapping both sides in a tuple switches distribution off, because the checked type is no longer a bare parameter. That is what [T] extends [never] is for: T extends never would distribute over an empty union and collapse to never without ever running the branch.

From a union to an intersection

ToIntersection builds that union of one-argument functions and then infers the argument back out of it:

type Step1 = ((arg: 'a') => void) | ((arg: 'b') => void)
// inferring `arg` from both signatures at once gives 'a' & 'b'

Function parameters are contravariant, so a type that is assignable to both signatures must accept both 'a' and 'b'. TypeScript resolves the inference by intersecting the candidates. For string literals 'a' & 'b' is never, which is exactly what the challenge's own test uses to detect a leftover union.

Naming the last member

The same machinery in return position behaves differently. U extends unknown ? () => U : never gives (() => 'test') | (() => 'hello') | (() => 'world'), and intersecting function types produces an overload set rather than a merged signature. When you then write extends () => infer L, inference against an overloaded type picks the last overload.

[object Object]

So LastInUnion hands you one concrete member of the union, and it is the one declared last. That ordering is an implementation detail of the compiler rather than a guarantee, which is why the tests accept any permutation. In practice it means the output comes out in source order.

The recursion

With one member named, the rest is an ordinary fold:

// T = 'test' | 'hello' | 'world'
// Last = 'world', Exclude<T, Last> = 'test' | 'hello'
// -> `${JoinStringUnion<'test' | 'hello', ', '>}, world`
//    `${`${JoinStringUnion<'test', ', '>}, hello`}, world`
//    'test, hello, world'

LastInUnion<T> extends infer Last extends string is doing two jobs at once. The infer Last binds the result so it is computed only once instead of three times in the body, and the trailing extends string narrows it so it can be dropped into a template literal without a cast.

Each step removes exactly one member with Exclude, so the union shrinks on every call and the recursion terminates after as many steps as there are members. The separator sits between the joined remainder and the last member, never at an end.

Edge cases the tests cover

This challenge is originally from here.

Share this challenge

Related Challenges

Learn the Concepts

Become a TypeScript Pro

Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.

Or start solving right away: explore all TypeScript challenges