I have created a unique conditional type that accurately generates a union of valid array indices:
type ArrayIndices<
N extends any[],
Acc extends number[] = []
> = Acc['length'] extends N['length']
? Acc[number]
: ArrayIndices<N, [...Acc, Acc['length']]>;
type Indices = ArrayIndices<['x', 'y', 'z']>;
// type Indices = 0 | 1 | 2
Furthermore, I have implemented it to modify the path creation conditional type on another page in order to handle arrays:
type Path<T, Key = keyof T> = Key extends keyof T
? T[Key] extends unknown[]
? `${Key & string}[${ArrayIndices<T[Key]>}]` | `${Key & string}`
: T[Key] extends object
? T[Key] extends infer R
? `${Key & string}.${Path<R, keyof R>}` | `${Key & string}`
: never
: `${Key & string}`
: never;
type Paths = Path<{ data: ['x', 'y', 'z'] }>;
// type Paths = "data" | "data[0]" | "data[1]" | "data[2]"
However, when attempting to apply it dynamically, there is a failure (testFunction
will only accept data
as a valid path prop, not other options like data[0]
):
const testObject = { data: ['x', 'y', 'z'] };
const testFunction = <T, P extends Path<T>>(obj: T, path: P) => {};
testFunction(testObject, 'data[0]');
// Argument of type '"data[0]"' is not assignable to parameter of type '"data"'
What could be causing this issue and how can it be resolved?