I have stumbled upon a certain Typescript syntax, which I find confusing. Here are two examples which were written by members of the Typescript team.
Example 1
type BoxedArray<T> = { array: T[] };
type Boxed<T> = T extends any[] ? BoxedArray<T[number]> : BoxedValue<T>;
type T21 = Boxed<number[]>; // BoxedArray<number>;
Here is how I'd naively read it:
// Boxed receives a type parameter - T = number[]
// Boxed passes BoxedArray an Array of T
// Therefore type T21 = BoxedArray<number[][]>
Example 2
type DeepReadonly<T> =
T extends any[] ? DeepReadonlyArray<T[number]> :
T extends object ? DeepReadonlyObject<T> :
T;
interface DeepReadonlyArray<T> extends ReadonlyArray<DeepReadonly<T>> {}
I understand that this syntax is somewhat similar to infer. I have seen it here and there, but I still don't really understand the structure, and couldn't find information about it.
T[K]is a lookup type, meaningT[K]is the type of value of the property ofTat keyK. (Note thatT[K]is notT[].) IfThas a numeric index signature (like an array) thenT[number]is the type of property stored atT's numeric index. IfTisArray<X>thenT[number]isX.