Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an array 'extend' a readonly array in TypeScript?

Tags:

typescript

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.

like image 725
michaeljsalo Avatar asked Oct 15 '25 21:10

michaeljsalo


1 Answers

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.

like image 128
Silvio Mayolo Avatar answered Oct 18 '25 13:10

Silvio Mayolo