Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
type CreateArray<V extends number, Arr extends unknown[] = []> =
Arr extends { length: V } ? Arr: CreateArray<V, [...Arr, 1]>;
type Add<A extends number, B extends number> = [...CreateArray<A>, ...CreateArray<B>]['length'];
type V = Add<2, 3>;
type Sub<A extends number, B extends number> = CreateArray<A> extends [...CreateArray<B>, ...infer Els] ? Els['length'] : never;
type V2 = Sub<10, 1>;
type Mul<A extends number, B extends number, Arr extends unknown[] = []> =
CreateArray<B> extends { length: 0 } ? Arr['length'] : CreateArray<B> extends [1, ...infer Els] ? Mul<A, Els['length'], [...Arr, ...CreateArray<A>]> : never;
type V3 = Mul<3, 7>;
@sebinsua
Copy link
Author

sebinsua commented Aug 25, 2022

Might be fun to do some other operations (Div, Mod etc), and to explain conceptually what is going on. Perhaps also to take a look at whether other people have achieved this in a worse or better way?

See: https://github.com/grantila/meta-types

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment