#8767Medium

Combination

Given an array of strings, do Permutation & Combination. Learn array type operations in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement Combination<T> which takes an array of strings and generates all possible permutations and combinations of those strings joined by spaces.

Challenge Instructions: Combination

Medium

Given an array of strings, do Permutation & Combination. It's also useful for the prop types like video controlsList

// expected to be `"foo" | "bar" | "baz" | "foo bar" | "foo bar baz" | "foo baz" | "foo baz bar" | "bar foo" | "bar foo baz" | "bar baz" | "bar baz foo" | "baz foo" | "baz foo bar" | "baz bar" | "baz bar foo"`
type Keys = Combination<['foo', 'bar', 'baz']>

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

ChallengeSolution
type cases = [
  Expect<
    Equal<
      Combination<['foo', 'bar', 'baz']>,
      | 'foo'
      | 'bar'
      | 'baz'
      | 'foo bar'
      | 'foo bar baz'
      | 'foo baz'
      | 'foo baz bar'
      | 'bar foo'
      | 'bar foo baz'
      | 'bar baz'
      | 'bar baz foo'
      | 'baz foo'
      | 'baz foo bar'
      | 'baz bar'
      | 'baz bar foo'
    >
  >,
  Expect<
    Equal<
      Combination<['apple', 'banana', 'cherry']>,
      | 'apple'
      | 'banana'
      | 'cherry'
      | 'apple banana'
      | 'apple cherry'
      | 'banana apple'
      | 'banana cherry'
      | 'cherry

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Combination<
  T extends string[],
  U extends string = T[number],
  S extends string = U,
> = S extends S ? S | `${S} ${Combination<[], Exclude<U, S>>}` : never

How it works:

This challenge helps you understand distributive conditional types and recursive union generation for permutation problems, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge