Skip to content

Instantly share code, notes, and snippets.

@jfet97
Last active February 19, 2022 22:33
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 jfet97/e8f26e77c99cee247855f754a31dfac3 to your computer and use it in GitHub Desktop.
Save jfet97/e8f26e77c99cee247855f754a31dfac3 to your computer and use it in GitHub Desktop.
Sum numbers, but in the type system!
type SameLenTuple<N extends number, T extends any[] = []> = number extends N
? never
: T["length"] extends N
? T
: SameLenTuple<N, [0, ...T]>;
type ConcatTuples<T1 extends any[], T2 extends any[]> = [...T1, ...T2];
type TupleToLen<T extends any[]> = T["length"];
type Sum<N extends number, M extends number> = [number] extends [N | M]
? number
: TupleToLen<ConcatTuples<SameLenTuple<N>, SameLenTuple<M>>> & number;
type three = Sum<0, 3>; // 3
type five = Sum<2, three>; // 2
type num = Sum<number, 2>; // number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment