Home > Software design >  Understanding result of indexed access types and extends
Understanding result of indexed access types and extends

Time:11-20

How does the indexed access type work when combined with extends keyword?

I can't explain why is result of following false:

type Test<T extends readonly any[]> =  T[number] extends true ? true: false
type R = Test<[true,true,false]>

Result:

false

CodePudding user response:

Let's go through this step by step.

T[number] will evaluate to true | true | false if T is [true,true,false]. TypeScript conveniently collapses this union down to just boolean.

boolean does not extend true, so the conditional evaluates to the false branch returning false.


You may have assumed that the union would be distributed over the conditional. But T[number] is not a naked generic type. No distribution takes place.

  • Related