This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
41. implement FindIndex<T, E>
type FindIndex<T extends any[], E> = { [K in keyof T]: T[K] extends E ? K : never;}[number] | never;
Explanation:
- We define a generic type
T
which extends an array of any typeT extends any[]
. - We further define a generic type
E
which represents the element we want to find the index of within arrayT
. - We use a mapped type to loop through the indices
K
of the arrayT
. - For each index
K
of arrayT
, we check whether the element at indexK
extends typeE
. - If the element at index
K
extends typeE
, we return indexK
. Otherwise, we returnnever
. - Finally, we use a union with
never
to filter out those indices that are not valid (i.e. those indices that returnednever
). - If no index is found which has the element that matches type E then it returns
never
.
Now, if we run the examples:
type A = [any, never, 1, '2', true]type B = FindIndex<A, 1> // 2type C = FindIndex<A, 3> // never
type B
should be 2
and type C
should be never
.