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).
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 -1Change the following code to make the test cases pass (no type check errors).
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>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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:
T, examining one element at a time using [infer First, ...infer Rest].Counter tuple accumulates elements to track the current index -- its length property gives us the numeric index.Equal<First, U> for strict type equality checking (this correctly distinguishes between any, number, string, etc.).Counter['length'] as the index.-1.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.