#5153Medium

IndexOf

Implement the type version of Array.indexOf, indexOf<T, U> takes an Array T, any U and returns the index of the first 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.indexOf, creating an IndexOf<T, U> type that takes a tuple T and a type U, returning the index of the first occurrence of U in T (or -1 if not found).

Challenge Instructions: IndexOf

Medium

Implement the type version of Array.indexOf, indexOf<T, U> takes an Array T, any U and returns the index of the first U in Array T.

type Res = IndexOf<[1, 2, 3], 2>; // expected to be 1
type Res1 = IndexOf<[2,6, 3,8,4,1,7, 3,9], 3>; // expected to be 2
type Res2 = IndexOf<[0, 0, 0], 2>; // expected to be -1

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

👋 Lifetime-License is leaving on August 10, 2026

Get it now for $29

One-time payment. Lifetime access to all pro challenges.

Loading...

Detailed Explanation

type IndexOf<T extends unknown[], U, Counter extends unknown[] = []> =
  T extends [infer First, ...infer Rest]
    ? Equal<First, U> extends true
      ? Counter['length']
      : IndexOf<Rest, U, [...Counter, unknown]>
    : -1;

How it works:

This challenge helps you understand recursive tuple traversal with index tracking and strict type equality, and how to apply these patterns in real-world scenarios.

This challenge is originally from here.

Share this challenge