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

ChallengeSolution
type cases = [
  Expect<Equal<IndexOf<[1, 2, 3], 2>, 1>>,
  Expect<Equal<IndexOf<[2, 6, 3, 8, 4, 1, 7, 3, 9], 3>, 2>>,
  Expect<Equal<IndexOf<[0, 0, 0], 2>, -1>>,
  Expect<Equal<IndexOf<[string, 1, number, 'a'], number>, 2>>,
  Expect<Equal<IndexOf<[string, 1, number, 'a', any], any>, 4>>,
  Expect<Equal<IndexOf<[string, 'a'], 'a'>, 1>>,
  Expect<Equal<IndexOf<[any, 1], 1>, 1>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

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