manidos
manidos

Reputation: 3464

Need help understanding a "distributive conditional types" example from the docs

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:

  1. How does T extends any[] work?

  2. What does the number mean in BoxedArray<T[number]>?

Upvotes: 0

Views: 23

Answers (1)

Zer0
Zer0

Reputation: 1690

  1. 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

  2. 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

Related Questions