I have a readonly array of strings and numbers. I want to have a reverse map object similar to how reverse mapping of enum
s work. In order to do this, I need to be able to find the index of T
within array A
.
const myArray = [1, '1+', 2, 3, '3+'] as const;
type MyArrayIndexes = {
[K in typeof myArray[number]]: IndexOf<typeof myArray, K>;
};
const myArrayIndexes: MyArrayIndexes = {
1: 0,
'1+': 1,
2: 2,
3: 3,
'3+': 4,
};
I was having trouble figuring out the definition of IndexOf<A extends readonly any[], T extends A[number]>
, but thought I'd play with it a bit longer before I asked SO. I figured it out, so I thought I'd share in case anyone else looked to do this.
My initial implementation was something like this, though originally it was using typeof myArray
directly rather than the template parameter A
and included some boneheaded, uninteresting mistakes.
type IndexOf<A extends readonly unknown[], T extends A[number]> = Extract<
{
[K in keyof A & number]: [A[K], K];
}[keyof A & number],
[T, number]
>[1];
When I tried to instantiate myArrayIndexes
, it was expecting every value to be never
.