Created
December 31, 2021 12:00
-
-
Save alii/af7c884ba8624e031b50a3c7b7aa9ae1 to your computer and use it in GitHub Desktop.
Multiplication math in TypeScript's type system
This file contains hidden or 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
// Multiplication in raw TypeScript. Please, please do not ever ever ever use this | |
type TupleOfLength< | |
T, | |
L extends number, | |
R extends T[] = [] | |
> = R["length"] extends L ? R : TupleOfLength<T, L, [...R, T]>; | |
type FlattenResult< | |
T extends 0[][], | |
I extends 0[] = [], | |
R extends 0[] = [] | |
> = T["length"] extends I["length"] | |
? R["length"] | |
: FlattenResult<T, [...I, 0], [...R, ...T[0]]>; | |
type multiply<a extends number, b extends number> = FlattenResult< | |
TupleOfLength<TupleOfLength<0, a>, b> | |
>; | |
type result = multiply<3, 999>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment