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.
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).
type Combination<
T extends string[],
U extends string = T[number],
S extends string = U,
> = S extends S ? S | `${S} ${Combination<[], Exclude<U, S>>}` : neverHow it works:
T into a union of its members using T[number], stored in U. The parameter S defaults to U and is used for distributive iterationS extends S is a distributive conditional type trick that iterates over each member of the union SS, it produces two results: the string itself (S), and that string followed by a space and all combinations of the remaining strings (${S} ${Combination<[], Exclude<U, S>>})Exclude<U, S> removes the current string from the available set, ensuring each string is used at most once per combinationExclude<U, S> results in never, at which point the template literal with never produces never and is eliminated from the unionT is passed as [] in recursive calls since only the union U matters after the initial conversionThis 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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount