#5317Medium

LastIndexOf

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).

Challenge Instructions: LastIndexOf

Medium

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> // -1

Change the following code to make the test cases pass (no type check errors).

Loading...

Detailed Explanation

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:

An 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.

Share this challenge

Join early, learn faster.

Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.

No spam, unsubscribe at any time. We respect your privacy.

Limited Availability

Only 27 Spots left

Early Access

Get 1 month early access

>75% Off

Pre-Launch discount