TypeScript supports conditional types, using 'extends' keyword and ternary operators.
Example conditional types that eval to true:
type C1 = 7 extends number ? true : false
type C2 = 7 extends number | string ? true : false
type C3 = 7 extends 7 | 'cat' | null ? true : false
type C4 = [1,2,3] extends [1,2,3] ? true : false
type C5 = any[] extends any[] ? true : false
I understand the conditions above (even if 'extends' seems odd in a non-OOP context).
The following conditions I don't understand:
type Q1 = any[] extends readonly any[] ? true : false // evals to true
type Q2 = readonly any[] extends any[] ? true : false // evals to false
Why does Q1 evaluate to true, and Q2 evaluate to false? I expected the opposite, as the readonly array seems 'more specific' than the general array.
What does 'extends' really mean in this context?
I am using TypeScript Playground to test these conditions.
extends
means "is a subtype of". Nothing more and nothing less. And "A
is a subtype of B
" means "every instance of A
is assignable to a variable of type B
". Again, nothing more and nothing less.
So the only question we need to ask is: is a T[]
assignable to readonly T[]
? Well, readonly T[]
allows us to access the elements of the array. T[]
allows us to access the elements of an array and also to mutate it. So T[]
supports all of the operations of readonly T[]
and then some. Hence, the relationship holds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With