In order to infer all types, you either should use as const for arr or pass it as a literal type to function instead passing reference.
type FindIndex<
T extends Array<{ type: string }>,
ExpectedType extends T[number]['type'],
> = {
[Prop in keyof T]:
(T[Prop] extends { type: infer Type }
? (Type extends ExpectedType
? Prop
: never
)
: never
)
}[number];
{
// 0
type Test = FindIndex<[{ type: 'a' }, { type: 'b' }], 'a'>
}
function GetType<
Type extends string,
Elem extends { type: Type },
Arr extends Elem[],
ExpectedType extends Arr[number]['type'],
>(arr: [...Arr], type: ExpectedType): FindIndex<Arr, ExpectedType>
function GetType<
Arr extends { type: string }[],
ExpectedType extends Arr[number]['type'],
>(arr: [...Arr], type: ExpectedType) {
return arr.find((item) => item.type === type)
}
const result = GetType([{ type: 'a' }, { type: 'b' }], 'a') // 0
Explanation
FindIndex - iterates through literaly infered tuple/array and checks whether type property extends ExpectedType. If yes - return Prop, in our case this is an index. Otherwise - never. So, without [number] at the end, you will end up with [0, never]. Indexing it by [number] returns 0 | never, which is basically equals to 0.
I have overloaded GetType in order to apply out FindIndex.
Also, as you might have noticed, in order to infer literal type, you should infer every prop of element. You should go from the bottom to the top.
First generic Type infers type property. Then, Elem infers
each element of the array. And finally Arr, thanks to variadic tuple types is fully infered.
You can find more information about tuple manipulations in my blog here and about type inference here