Reputation: 3464
Here's a link to the example
Here's a link to the playground
Here's the code:
type BoxedValue<T> = { value: T };
type BoxedArray<T> = { array: T[] };
type Boxed<T> = T extends any[] ? BoxedArray<T[number]> : BoxedValue<T>;
type T1 = Boxed<string>;
type T2 = Boxed<number[]>;
type T3 = Boxed<string | number[]>;
My questions are:
How does T extends any[]
work?
What does the number
mean in BoxedArray<T[number]>
?
Upvotes: 0
Views: 23
Reputation: 1690
Well how does it work? It's just what stands there: it checks if T is (or is extended) an array => evaluates as true if T is an array
That's a "generic index" (It has a different name but I can't remember that one any more), I think an example makes it pretty clear:
const list = [1, 2, 3] as const;
type a = typeof list[number]; //evaluates to 1 | 2 | 3
type l = any[];
type m = l[number]; //evaluates to any
Upvotes: 1