0

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>;

source

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>> {}

source

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.

3
  • 1
    The type T[K] is a lookup type, meaning T[K] is the type of value of the property of T at key K. (Note that T[K] is not T[].) If T has a numeric index signature (like an array) then T[number] is the type of property stored at T's numeric index. If T is Array<X> then T[number] is X. Commented Jan 28, 2019 at 17:09
  • Thanks Jcalz, Your comment made the syntax very clear. Why did you comment instead of answer? Commented Jan 28, 2019 at 17:19
  • "Why did you comment instead of answer?" Good question. Commented Jan 28, 2019 at 17:21

1 Answer 1

1

The type T[K] is a lookup type, meaning T[K] is the type of value of the property of T at key K. (Note that T[K] is not T[].) If T has a numeric index signature (like an array) then T[number] is the type of property stored at T's numeric index. Specifically, if T is Array<X> then T[number] is X. (That does lead to the confusing looking string[][number] being the same as string). Hope that helps. Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.