Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active September 3, 2022 18:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sebinsua/f779675ff30d515b93c5fc69f1c0d7ef to your computer and use it in GitHub Desktop.
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