Yuzhe's Blog

yuzhes

Combination key type

Combination key type

Problem Link

Problem

Combine multiple modifier strings with a union type into a new type. The order doesn’t matter.

// input
type Key = 'cmd' | 'ctrl' | 'opt' | 'fn'

// output — all non-empty combinations joined with '+'
type CombinationKeyType<T extends string> = ... // e.g. 'cmd', 'cmd+ctrl', 'cmd+ctrl+opt', ...

Solution

type Combination<T extends string, U extends string = T> =
  T extends any
    ? T | `${T}+${Combination<Exclude<U, T>>}`
    : never

type CombinationKeyType<T extends string> = Combination<T>

How it works:

  1. Distribute over T — for each member T we produce:
    • T alone (single key)
    • T + '+' + (combination of remaining keys) — recursion excludes the current key to avoid repetition.
  2. Exclude<U, T> removes the current key from the pool so we never use the same key twice.
  3. When the excluded pool is empty, Combination<never> resolves to never, terminating the recursion.

Key Takeaways