Skip to content

Instantly share code, notes, and snippets.

@ahamed
Created July 21, 2022 16:47
Show Gist options
  • Select an option

  • Save ahamed/2d7b0142f2a57b923b7876006fefcecc to your computer and use it in GitHub Desktop.

Select an option

Save ahamed/2d7b0142f2a57b923b7876006fefcecc to your computer and use it in GitHub Desktop.
Find an item's index from a tuple.
type IncrementByOne<N extends number, T extends unknown[] = []> =
T['length'] extends N
? [...T, unknown]['length']
: IncrementByOne<N, [...T, unknown]>;
type IndexOf<T extends unknown[], U extends unknown, I extends number = 0> =
I extends T['length']
? -1
: T[I] extends U
? I
: IndexOf<T, U, IncrementByOne<I>>;
type NotFound = IndexOf<[3, 4, 5, 3], 2>; // -1
type FoundIndex = IndexOf<[3, 4, 5, 2], 5>; // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment