Skip to content

Instantly share code, notes, and snippets.

@alii
Created December 31, 2021 12:00
Show Gist options
  • Save alii/af7c884ba8624e031b50a3c7b7aa9ae1 to your computer and use it in GitHub Desktop.
Save alii/af7c884ba8624e031b50a3c7b7aa9ae1 to your computer and use it in GitHub Desktop.
Multiplication math in TypeScript's type system
// 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