Created
July 21, 2022 16:47
-
-
Save ahamed/2d7b0142f2a57b923b7876006fefcecc to your computer and use it in GitHub Desktop.
Find an item's index from a tuple.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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