new to TypeScript, was searching for a way to define a fixed size array and came across this:
type Tuple<T, N extends number> = N extends N ? number extends N ? T[] : _TupleOf<T, N, []> : never;
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>;
type Tuple9<T> = Tuple<T, 9>;
type Board9x9<P> = Tuple9<Tuple9<P>>;
...which obtains the desired result using recursive conditional types.
I was trying to understand the syntax that is being used, and I couldn't really understand what is happening behind the scenes particularly in this point: R['length'] extends N
.
I understood that it checks if the array is of the desired length and if not it'll recursively call _TupleOf
with an extra element until that condition becomes true. but why is that happening?
I searched for answers but couldn't really find anything useful.
Does R['length']
return the actual length as a number if it is applied to a type? And why extends
seems to behaves like a ==
operator in this case?
I've also tried double-checking if it behaves as i understood in this playground (you can hover over b
and c
to check the types) and it seems it does, still can't understand why tho.
Any link or explanation? thanks in advance!