Implement the type version of ```Array.lastIndexOf```, ```LastIndexOf<T, U>``` takes an Array ```T```, any ```U``` and returns the index of the last ```U``` in Array ```T``` Learn array type operations in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement the type-level version of Array.lastIndexOf, where LastIndexOf<T, U> takes a tuple T and a type U, and returns the index of the last occurrence of U in T (or -1 if not found).
Implement the type version of Array.lastIndexOf, LastIndexOf<T, U> takes an Array T, any U and returns the index of the last U in Array T
For example:
type Res1 = LastIndexOf<[1, 2, 3, 2, 1], 2> // 3
type Res2 = LastIndexOf<[0, 0, 0], 2> // -1Change the following code to make the test cases pass (no type check errors).
type LastIndexOf<T extends any[], U> =
T extends [...infer Rest, infer Last]
? Equal<Last, U> extends true
? Rest['length']
: LastIndexOf<Rest, U>
: -1;How it works:
[...infer Rest, infer Last], checking the last element firstEqual utility to perform an exact type equality check between Last and U, which correctly distinguishes between types like number and anyRest['length'] gives the correct zero-based index of that element, since the rest of the tuple before the matched element has exactly that many itemsRest tuple until the base case is reached, returning -1An alternative approach using forward iteration:
type LastIndexOf<T extends any[], U, Result extends number = -1> =
T extends [infer First, ...infer Rest]
? Equal<First, U> extends true
? LastIndexOf<Rest, U, T extends { length: infer L extends number } ? [...Rest, any]['length'] extends infer _ ? Result extends -1 ? Subtract<T['length'], Rest['length']> : Subtract<T['length'], Rest['length']> : never : never>
: LastIndexOf<Rest, U, Result>
: Result;The first approach is cleaner since iterating from the right naturally finds the last index first.
This challenge helps you understand recursive tuple manipulation and type-level indexing, and how to apply these concepts in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount