Получить индексы у массива в TypeScript (как keyof у объектов)

Рейтинг: 1Ответов: 1Опубликовано: 06.03.2023

У меня есть массив, допустим это будет:

const testArray = [
    "test1",
    "test2",
    "test3",
    "test4"
] as const;

Могу ли я получить в тип индексы ключей? Что-то типо keyof у объектов:

type arrayIndex = keyof typeof testArray; // arrayIndex: 0 | 1 | 2 | 3

Ответы

▲ 2Принят

Создать тип из индексов элементов массива возможно:

const testArray = [
    "test1",
    "test2",
    "test3",
    "test4"
] as const;
// Создадим конструктор для типов
type IndicesType<T extends readonly string[]> = Exclude<Partial<T>["length"], T["length"]>
// Создаем тип
type ArrayIndex = IndicesType<typeof testArray>;

ArrayIndex -> 0 | 1 | 2 | 3

Если надо сделать один раз с жестким указаним типа, можно так

type ArrayIndex = Exclude<Partial<typeof testArray>["length"], typeof testArray["length"]>;

Если мы создадим тип для переменной, то можно сделать так:

type TestType = readonly [string, string, string, string];

const testArray: TestType = [
    "test1",
    "test2",
    "test3",
    "test4"
] as const;

type ArrayIndex = Indices<TestType>;

Тестируем:

function tst(idx: ArrayIndex) {
    console.log(testArray[idx]);
}

tst(3); // Успех
tst(9); // Выдаст ошибку