sindresorhus/type-fest

IndexOf - Find the index of a type in a tuple

Open

#535 aberto em 26 de dez. de 2022

Ver no GitHub
 (3 comments) (1 reaction) (0 assignees)TypeScript (471 forks)batch import
help wantedtype addition

Métricas do repositório

Stars
 (12.328 stars)
Métricas de merge de PR
 (Mesclagem média 3d 5h) (11 fundiu PRs em 30d)

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

Guia do colaborador