Создать тип из индексов элементов массива возможно:
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); // Выдаст ошибку