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
Twhich extends an array of any typeT extends any[]. - We further define a generic type
Ewhich represents the element we want to find the index of within arrayT. - We use a mapped type to loop through the indices
Kof the arrayT. - For each index
Kof arrayT, we check whether the element at indexKextends typeE. - If the element at index
Kextends typeE, we return indexK. Otherwise, we returnnever. - Finally, we use a union with
neverto 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.