Last active
February 19, 2022 22:33
-
-
Save jfet97/e8f26e77c99cee247855f754a31dfac3 to your computer and use it in GitHub Desktop.
Sum numbers, but in the type system!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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