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).
Launch price: $19 $29
One-time payment. Lifetime access to all pro challenges.
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.
Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.