#21106Medium

Combination key type

1. Combine multiple modifier keys, but the same modifier key combination cannot appear. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement Combs<T> which generates all unique two-key combinations from a tuple of modifier keys, preserving the original order so that 'cmd ctrl' is valid but 'ctrl cmd' is not.

Challenge Instructions: Combination key type

Medium
  1. Combine multiple modifier keys, but the same modifier key combination cannot appear.
  2. In the ModifierKeys provided, the priority of the previous value is higher than the latter value; that is, cmd ctrl is OK, but ctrl cmd is not allowed.

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

ChallengeSolution
type ModifierKeys = ['cmd', 'ctrl', 'opt', 'fn']
type CaseTypeOne =
  | 'cmd ctrl'
  | 'cmd opt'
  | 'cmd fn'
  | 'ctrl opt'
  | 'ctrl fn'
  | 'opt fn'

type cases = [Expect<Equal<Combs<ModifierKeys>, CaseTypeOne>>]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type Combs<T extends any[]> = T extends [infer First extends string, ...infer Rest extends string[]]
  ? `${First} ${Rest[number]}` | Combs<Rest>
  : never

How it works:

This challenge helps you understand recursive type processing of tuples combined with template literal types and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge