Skip to content

Instantly share code, notes, and snippets.

@palladin
Created June 2, 2022 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palladin/f55c88b3d5cb1427857fbdf9cd475617 to your computer and use it in GitHub Desktop.
Save palladin/f55c88b3d5cb1427857fbdf9cd475617 to your computer and use it in GitHub Desktop.
Type level PowerSet in TypeScript
type Append<T, TArray> = TArray extends [infer TCurrent, ...infer Rest] ?
TCurrent extends any[] ? [[T, ...TCurrent], ...Append<T, Rest>] : never
: []
type PowerSet<TArray extends any[]> =
TArray extends [infer TCurrent, ...infer Rest] ? [...Append<TCurrent, PowerSet<Rest>>, ...PowerSet<Rest>] : [[]]
type Test = PowerSet<[1, 2, 3]> // [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment