Combination key type
Less than 1 minuteTC-Medium
Combination key type
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:
- Distribute over
T— for each memberTwe produce:Talone (single key)T + '+' + (combination of remaining keys)— recursion excludes the current key to avoid repetition.
Exclude<U, T>removes the current key from the pool so we never use the same key twice.- When the excluded pool is empty,
Combination<never>resolves tonever, terminating the recursion.
Key Takeaways
- Distributing over a union (
T extends any ? ... : never) is the standard way to process each member. - Keeping a separate
Uparameter for the full union while distributing onTlets us doExclude<U, T>cleanly. - The recursion naturally generates all ordered subsets; since
+is the separator,'a+b'and'b+a'are distinct types — which is intentional for key combinations.
