sindresorhus/type-fest

IndexOf - Find the index of a type in a tuple

Open

#535 opened on Dec 26, 2022

View on GitHub
 (3 comments) (1 reaction) (0 assignees)TypeScript (12,328 stars) (471 forks)batch import
help wantedtype addition

Description

Can be useful sometimes to find the index of a type in a readonly array (tuple), IE:

type Tuple = [T1, T2, T3];
type Index = IndexOf<Tuple, T1> // '0';

This works:

export type Indexes<V extends readonly any[]> = {
  [K in Exclude<keyof V, keyof Array<any>>]: K;
};
export type IndexOf<V extends readonly any[], T> = {
  [I in keyof Indexes<V>]: V[I] extends T
    ? T extends V[I]
      ? I
      : never
    : never;
}[keyof Indexes<V>];

It's possible to do some cool stuff with this

Contributor guide