#4260Medium

AllCombinations

Implement type ```AllCombinations<S>``` that return all combinations of strings which use characters from ```S``` at most once. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement AllCombinations<S> that returns all possible permutations and combinations of characters from the string S, using each character at most once.

Challenge Instructions: AllCombinations

Medium

Implement type AllCombinations<S> that return all combinations of strings which use characters from S at most once.

For example:

type AllCombinations_ABC = AllCombinations<'ABC'>;
// should be '' | 'A' | 'B' | 'C' | 'AB' | 'AC' | 'BA' | 'BC' | 'CA' | 'CB' | 'ABC' | 'ACB' | 'BAC' | 'BCA' | 'CAB' | 'CBA'

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

ChallengeSolution
type cases = [
  Expect<Equal<AllCombinations<''>, ''>>,
  Expect<Equal<AllCombinations<'A'>, '' | 'A'>>,
  Expect<Equal<AllCombinations<'AB'>, '' | 'A' | 'B' | 'AB' | 'BA'>>,
  Expect<
    Equal<
      AllCombinations<'ABC'>,
      | ''
      | 'A'
      | 'B'
      | 'C'
      | 'AB'
      | 'AC'
      | 'BA'
      | 'BC'
      | 'CA'
      | 'CB'
      | 'ABC'
      | 'ACB'
      | 'BAC'
      | 'BCA'
      | 'CAB'
      | 'CBA'
    >
  >,
  Expect<
    Equal<
      AllCombinations<'ABCD'>,
      | ''
      | 'A'
      | 'B'
      | 'C'
      | 'D'
      | 'AB'
      | 'AC'
      | 'AD'
   

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type StringToUnion<S extends string> = S extends `${infer First}${infer Rest}`
  ? First | StringToUnion<Rest>
  : never
 
type Combinations<U extends string, S extends string = U> =
  S extends S
    ? '' | `${S}${Combinations<Exclude<U, S>>}`
    : never
 
type AllCombinations<S extends string> = Combinations<StringToUnion<S>>

How it works:

This challenge helps you understand distributive conditional types, recursive type generation, and template literal types, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge