Skip to content

Instantly share code, notes, and snippets.

@saiashirwad
Created February 1, 2025 13:54
Show Gist options
  • Save saiashirwad/d222ebdbe115df9673f645d6c49e39eb to your computer and use it in GitHub Desktop.
Save saiashirwad/d222ebdbe115df9673f645d6c49e39eb to your computer and use it in GitHub Desktop.
webstorm typescript tuple arithmetic
type buildTuple<
n extends number,
acc extends any[] = [],
> = acc["length"] extends n ? acc : buildTuple<n, [...acc, 0]>;
type add<a extends number, b extends number> = [
...buildTuple<a>,
...buildTuple<b>,
]["length"] &
number;
type subtract<a extends number, b extends number> = buildTuple<a> extends [
...buildTuple<b>,
...infer rest,
]
? rest["length"]
: never;
type addResult = add<2, 5>;
type subResult = subtract<5, 2>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment