Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I make an Array readonly this way in TypeScript?

The documentation shows (#ReadOnlyArray) how to do it using an interface, but as I am exploring the language I wondered why does this not work as well ?

type TraverseTuple<T extends Array<unknown>> = {
     readonly [P in keyof T]: T[P];
}

const test: TraverseTuple<[string, number, string, number]> = ['s', 1, 'o', 2];

test[1] = 0; // not readonly !
like image 263
millsp Avatar asked Oct 27 '25 06:10

millsp


2 Answers

There is a built-in read-only array type, which makes arrays read only (unless asserted back to a plain array).

const test: ReadonlyArray<string|number> = ['s', 1, 'o', 2];

test[1] = 0;

But, for tuples you need to create an explicit type, like this:

const test: Readonly<{ 0: string, 1: number, 2: string, 3: number }> = ['s', 1, 'o', 2];

test[1] = 1;
like image 64
Fenton Avatar answered Oct 28 '25 21:10

Fenton


This behavior is specifically not supported. The ability to map tuples was just recently introduces to typescript 3.1 with this PR. From the PR:

A readonly, -readonly, or +readonly annotation in a homomorphic mapped type currently has no effect on array or tuple elements (we might consider mapping from Array to ReadonlyArray and vice versa, although that technically isn't structure preserving because it adds or removes methods).

like image 20
Titian Cernicova-Dragomir Avatar answered Oct 28 '25 20:10

Titian Cernicova-Dragomir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!