Skip to content

Instantly share code, notes, and snippets.

@betafcc
Last active June 24, 2024 10:02
Show Gist options
  • Save betafcc/f9084dd9f42ffea59ad6f2ff366b864f to your computer and use it in GitHub Desktop.
Save betafcc/f9084dd9f42ffea59ad6f2ff366b864f to your computer and use it in GitHub Desktop.
Typescript Union Permutation, count of keys in an object, count of cases in an Union
/**
* @example
* type P = Permutation<1 | 2 | 3>
* // [1, 2, 3] | [1, 3, 2] | [2, 1, 3] | [2, 3, 1] | [3, 1, 2] | [3, 2, 1]
*/
export type Permutation<U, T = U> = [U] extends [never]
? []
: T extends unknown
? [T, ...Permutation<Exclude<U, T>>]
: never
/**
* @example
* type C = UnionCount<'a' | 'b' | 'c'>
* // 3
*/
export type UnionCount<U> = Permutation<U>['length']
/**
* @example
* type C = KeyCount<{ x: 1, y: 2 }>
* // 2
*/
export type KeyCount<T> = UnionCount<keyof T>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment