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

Launch price: $19 $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

Stay Updated

Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.

No spam, unsubscribe at any time.